Reputation: 13
I am a beginner in R and I have a large dataset, part of which is:
Hours<- c(1:14)
Measure<- c(5,4,5,5,4,5,5,6,7,6,5,4,5,5)
log6<- data.frame (Hours, Measure)
I would like to read 3 consecutive rows and check if log6$Measure<=5 in all 3 rows.
Then add another column with True or False based on the previous condition.
Expected Output:
Hours Measure Result
1 1 5 -
2 2 4 -
3 3 5 TRUE
4 4 5 TRUE
5 5 4 TRUE
6 6 5 TRUE
7 7 5 TRUE
8 8 6 FALSE
9 9 7 FALSE
10 10 6 FALSE
11 11 5 FALSE
12 12 4 FALSE
13 13 5 TRUE
14 14 5 TRUE
Any suggestions?
Upvotes: 1
Views: 199
Reputation: 887881
We can use rollapply
from library(zoo)
library(zoo)
log6$Result <- rollapply(log6$Measure, 3, FUN=
function(x) all(x<=5), fill=NA, align="right")
log6$Result
#[1] NA NA TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
A variant suggested by @jogo
!!(rollapply(data=(log6$Measure < 6), width=3, FUN=prod,
by=1, fill=NA, align="right"))
and another:
rollapply(log6$Meassure < 6, 3, all, fill=NA, align="right")
Or from @nicola
rollmax(log6$Measure,3, fill=NA, align="right") <=5
Upvotes: 5