Given the following sample data table:
library(data.table)
DT <- fread("grp y exclude
a 1 0
a 2 0
a 3 0
a 4 1
a 5 0
a 7 1
a 8 0
a 9 0
a 10 0
b 1 0
b 2 0
b 3 0
b 4 1
b 5 0
b 6 1
b 7 1
b 8 0
b 9 0
b 10 0
c 5 1
d 1 0")
I want to choose
- by group
grp - all rows having
y==5 - and up to two lines before and after each line of 2 in the group.
- but 3. only those lines that have
exclude==0.
Assuming each group has a maximum of one row s y==5, this will give the desired result for 1.-3 .:
idx <- -2:2
(row_numbers <- DT[,.I[{
x <- rep(which(y==5),each=length(idx))+idx
x[x>0 & x<=.N]
}], by=grp]$V1)
DT[row_numbers]
However, how do I enable 4. to get
? I feel like I'm near, but I think I looked at headand whiches too long , so I would be grateful for some fresh ideas.
lukeA source
share