1

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

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
ILoveCoding
  • 866
  • 1
  • 9
  • 18
  • This is very close to http://stackoverflow.com/questions/13155609/returning-above-and-below-rows-of-specific-rows-in-r-dataframe/13156365#13156365 – flodel Feb 07 '13 at 18:32
  • Indeed... let's hope this question will help user end up on the right answer; my searches had not yielded this result.. – ILoveCoding Feb 07 '13 at 18:41

1 Answers1

4

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))
juba
  • 47,631
  • 14
  • 113
  • 118