数据
df1 <- structure(list(smp = 1:17, x = c(609, 609, 609, 625, 625, 608,
608, 608, 608, 608, 608, 608, 630, 631, 605, 603, 602), y = c(449,
446, 446, 460, 455, 445, 445, 445, 445, 445, 445, 445, 459, 459,
446, 448, 452), blink = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE,
TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE,
FALSE)), .Names = c("smp", "x", "y", "blink"), class = "data.frame", row.names = c(NA, -17L))
在这个有多个 TRUE 值的数据实例中,可能需要采用不同的方法进行索引,以在感兴趣的条件之前和之后实际获取值,因为上述基本方法将返回感兴趣的条件内的值。
考虑您需要在条件之前和之后的 SpatialPoints,然后想要将之前的距离与给定点进行比较,并将之后的条件与给定点进行比较。在那种情况下,您想要(正好)条件之前和(正好)之后的点,并且可能不想要中间点。类似于上面 akrun 的回答,这建议同时调整左侧 (LHS) 和右侧 (RHS) 的索引。调整 LHS 和 RHS 的索引提供了对感兴趣条件(之前或之后)的“外部性”进行第二次逻辑测试的机会,在一个之后有多个 T 的情况下,上述方法无法解决。 F 后跟一个 F,即 F、T、T、T、F、F。
head(df1, n = 17)
smp x y blink
1 1 609 449 FALSE
2 2 609 446 FALSE
3 3 609 446 TRUE
4 4 625 460 FALSE
5 5 625 455 FALSE
6 6 608 445 TRUE
7 7 608 445 TRUE
8 8 608 445 FALSE
9 9 608 445 FALSE
10 10 608 445 TRUE
11 11 608 445 TRUE
12 12 608 445 TRUE
13 13 630 459 FALSE
14 14 631 459 FALSE
15 15 605 446 TRUE
16 16 603 448 TRUE
17 17 602 452 FALSE
df1[c('pre_x', 'pre_y', 'post_x', 'post_y')] <- NA
在这种情况下,pre_x/pre_y、post_x/post_y 最终将是 cbind 坐标,然后是 SpatialPoints;但是,这是在确定之前和之后的内容之后发生的。您的用例可能不同,但逻辑应该成立。
indx_1 <- which(df1$blink)
indx_1
[1] 3 6 7 10 11 12 15 16
然后使用indx_1计算pre_x、pre_y、post_x、post_y:
df1$pre_x[indx_1 - 1] <- df1$x[indx_1 - 1]
df1$pre_y[indx_1 - 1] <- df1$y[indx_1 - 1]
df1$post_x[indx_1 + 1] <- df1$post_x[indx_1 + 1]
df1$post_y[indx_1 + 1] <- df1$post_y[indx_1 + 1]
> head(df1, n = 17)
smp x y blink pre_x pre_y post_x post_y
1 1 609 449 FALSE NA NA NA NA
2 2 609 446 FALSE 609 446 NA NA
3 3 609 446 TRUE NA NA NA NA
4 4 625 460 FALSE NA NA 625 460
5 5 625 455 FALSE 625 455 NA NA
6 6 608 445 TRUE 608 445 NA NA
7 7 608 445 TRUE NA NA 608 445
8 8 608 445 FALSE NA NA 608 445
9 9 608 445 FALSE 608 445 NA NA
10 10 608 445 TRUE 608 445 NA NA
11 11 608 445 TRUE 608 445 608 445
12 12 608 445 TRUE NA NA 608 445
13 13 630 459 FALSE NA NA 630 459
14 14 631 459 FALSE 631 459 NA NA
15 15 605 446 TRUE 605 446 NA NA
16 16 603 448 TRUE NA NA 603 448
17 17 602 452 FALSE NA NA 602 452
现在所需的值被写入感兴趣的条件之外
并可靠地报告前后值。此外,
前索引 (indx_2) 和后 (indx_3) 可用于选择进一步处理,在我的情况下为 SpatialPoints 制作坐标。
indx_2 <- which(!df1$blink & !is.na(df1$pre_x))
indx_3 <- which(!df1$blink & !is.na(df1$post_x))
coords_pre <- cbind(x = df1$pre_x[indx_2], y = df1$pre_y[indx_2])
coords_post <- cbind( x = df1$post_x[indx_3], y = df1$post_y[indx_3])
library(sp)
pre_blink_sp <- SpatialPoints(coords_pre)
> summary(pre_blink_sp)
Object of class SpatialPoints
Coordinates:
min max
x 608 631
y 445 459
Is projected: NA
proj4string : [NA]
Number of points: 4
已经整理好如何在 base 中执行此操作,尽管很乏味,df1$smp
是否有 setkey(),因为我现在试图弄清楚如何在 data.table 中完成相同的操作。