1

In my dataframe I would like to select a row based on some logic, and then return a dataframe with the selected row PLUS the next 'N' rows.

So, I have this: (a generic example)

workingRows <- myData[which(myData$Column1 >= myData$Column2 & myData$Column3 <= myData$Column4), ]

Which returns me the correct "starting values". How can I get the "next" 5 values based on each of the starting values?

funk101
  • 163
  • 4
  • 13
  • For next time: Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Jul 16 '16 at 17:25
  • 1
    Ok, I got it, next time I'll give a minimal dataset for people to test against. – funk101 Jul 16 '16 at 17:53

1 Answers1

5

We can use rep to get the next 5 rows, sort it and if there are any duplicates from overlaps, wrap it with unique and subset the 'myData'.

i1 <-  which(myData$Column1 >= myData$Column2 & myData$Column3 <= myData$Column4)
myData[unique(sort(i1 + rep(0:5, each = length(i1)))),]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Oh, good, I was just about to suggest adding unique, but you saw the potential for overlaps. – IRTFM Jul 16 '16 at 17:06