mercredi 21 juin 2017

Including lag() in ifelse() function in R

I have sec-by-sec data and would like to create a new variable "category" based on some conditions on variable "acceleration". To be specific, if "acceleration <= -2 OR (acceleration for the current second <-1 & acceleration for the previous second <-1 & acceleration for the previous two second <-1), then "category" equals 1, otherwise it's 0.

I'm guessing I should use lag() somewhere in the code to account for the time lag, but it's just doesn't work... Can someone point out my mistake and correct me? Thanks...

 df$category <- ifelse(df$acceleration<=-2 | 
                     (df$acceleration<-1 & lag(df$acceleration, 1)<-1 & 
                      lag(df$acceleration, 2) < -1), 1,0)

Aucun commentaire:

Enregistrer un commentaire