1

我还没有找到一种简单的方法来在我想要选择的行周围包含一些上下文(n 相邻行)。
我或多或少地试图镜像 grep 的 -C 选项来选择 data.frame 的某些行。

前任:

a= data.frame(seq(1:100))  
b = c(50, 60, 61)

假设我想要在 b 中索引的行周围有 2 行的上下文;所需的输出应该是具有行 48、49、50、51、52、58、59、60、61、62、63 的数据框子集

4

1 回答 1

4

你可以做这样的事情,但可能有一种更优雅的方法来计算索引:

a= data.frame(seq(1:100))  
b = c(50, 60, 61)
context <- 2
indices <- as.vector(sapply(b, function(v) {return ((v-context):(v+context))}))
a[indices,]

这使 :

 [1] 48 49 50 51 52 58 59 60 61 62 59 60 61 62 63

编辑:正如@flodel 指出的那样,如果索引可能重叠,您必须添加以下行:

indices <- sort(unique(indices))
于 2013-02-07T18:27:20.610 回答