问题
I haven't been able to figure out an easy way to include some context ( n adjacent rows ) around the rows I want to select.
I am more or less trying to mirror the -C option of grep to select some rows of a data.frame.
Ex:
a= data.frame(seq(1:100))
b = c(50, 60, 61)
Let's say I want a context of 2 lines around the rows indexed in b; the desired output should be the data frame subset of a with the rows 48,49,50,51,52,58,59,60,61,62,63
回答1:
You can do something like this, but there may be a more elegant way to compute the indices :
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,]
Which gives :
[1] 48 49 50 51 52 58 59 60 61 62 59 60 61 62 63
EDIT : As @flodel points out, if the indices may overlap you must add the following line :
indices <- sort(unique(indices))
来源:https://stackoverflow.com/questions/14758243/subset-rows-context