subset rows + context

心已入冬 提交于 2019-12-09 14:05:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!