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?
df$category <- ifelse(df$acceleration<=-2 |
(df$acceleration<-1 & lag(df$acceleration, 1)<-1 &
lag(df$acceleration, 2) < -1), 1,0)
Using dplyr
:
df %>%
mutate(acc1 = lag(acceleration),
acc2 = lag(acc1),
category = ifelse( acceleration <= -2 |
(acceleration < -1 &
acc1 < -1 & acc2 < -1),
1, 0)) %>%
select(-acc1, acc2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.