HoHoHo HoHoHo - 1 month ago 10
R Question

Select n rows around every specific row meeting condition

I have a

DF


A B C
NA 0.1 100
NA 0.2 200
1 0.3 300
NA 0.4 400
NA 0.5 500
1 0.5 600
NA 0.6 700
NA 0.6 800


I need to select all rows if
DF$A=1
. Additionally, I need to select all rows below and above
DF$A=1
rows so that
DF$C-100
&
DF$C+100

So that the output will be

A B C
NA 0.2 200
1 0.3 300
NA 0.4 400
NA 0.5 500
1 0.5 600
NA 0.6 700


I would expect it should be something like this

if (DF$A==1) print(c(DF[DF$C-100 & DF$C+100, ]))


But of course it doesnt work..
Thank you for any clues.

Answer

You can do this by first finding the indices for which df$A==1, and then concatenating all indices +/- 1 from that:

ind <- which(df$A==1)
out <- df[sort(unique(c(ind-1,ind,ind+1))),]
##   A   B   C
##2 NA 0.2 200
##3  1 0.3 300
##4 NA 0.4 400
##5 NA 0.5 500
##6  1 0.5 600
##7 NA 0.6 700

Here, we find all the unique indices from the concatenated indices, and we sort them for the subset. If you really don't care about the order, you don't need to sort, but the unique is necessary for handling the overlap.