Question

Say I have a data frame

df <- data.frame(A=c(1,3,1,4,2,2,5,3,1,7,8),b=c(10:20),c=c(20:30))

and I want to extract all the consecutive rows whose sum in column A is 4.

I can run through with rollapply from package zoo and easily find out if there are any such rows with

rollapply(df$A,2,function(x)(ifelse(sum(x)==4,print("YES"),print("NO"))))

But I want to be able to just take out the rows for which this condition is true and put them in another data frame

sum4 <- data.frame(A=c(1,3,1,2,2,3,1),B=c(10,11,12,14,15,17,18),C=c(20,21,22,24,25,27,28))

Is this possible, and if so, how?

Was it helpful?

Solution

Save the results of your rolling sum as something, then construct a vector containing the rows on which those sums ==4 are based (row, row+1)

rs2 <- with(df,rollapply(A, 2, sum, fill = NA))
s4 <- sort(unique(c(s4 <- which(rs2==4),s4+1)))
subset the appropriate rows
df[s4,]
#   A  b  c
# 1 1 10 20
# 2 3 11 21
# 3 1 12 22
# 5 2 14 24
# 6 2 15 25
# 8 3 17 27
# 9 1 18 28
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top