I have this data
ratings <- data.frame(Rating = c(0,99,99,99,99,99,99,99,0,99,99,99,99,99,99,99,99,99,99,99),
Trial = c(1,NA,NA,NA,NA,NA,NA,NA,2,NA,NA,NA,NA,NA,3,NA,NA,NA,NA,NA))
Rating Trial
0 1
99 NA
99 NA
99 NA
99 NA
99 NA
99 NA
99 NA
0 2
99 NA
99 NA
99 NA
99 NA
99 NA
1 3
99 NA
99 NA
99 NA
99 NA
99 NA
I want to select the four consecutive rows after the second trial.
What I've tried
ratings |>
mutate(var = ifelse(lag(Trial, n = 4L) == 2, 1, 0))
But, reasonably so, I am selecting only the 4th row.
What I want to get to:
Rating Trial var
0 1 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
0 2 0
99 NA 1
99 NA 1
99 NA 1
99 NA 1
99 NA 0
1 3 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
99 NA 0
Any ideas? Thanks.
CodePudding user response:
ratings <- data.frame(Rating = c(0,99,99,99,99,99,99,99,0,99,99,99,99,99,99,99,99,99,99,99),
Trial = c(1,NA,NA,NA,NA,NA,NA,NA,2,NA,NA,NA,NA,NA,3,NA,NA,NA,NA,NA))
library(dplyr, warn.conflicts = FALSE)
ratings %>%
mutate(var = replace(rep(0, n()), which(Trial == 2) 1:4, 1))
#> Rating Trial var
#> 1 0 1 0
#> 2 99 NA 0
#> 3 99 NA 0
#> 4 99 NA 0
#> 5 99 NA 0
#> 6 99 NA 0
#> 7 99 NA 0
#> 8 99 NA 0
#> 9 0 2 0
#> 10 99 NA 1
#> 11 99 NA 1
#> 12 99 NA 1
#> 13 99 NA 1
#> 14 99 NA 0
#> 15 99 3 0
#> 16 99 NA 0
#> 17 99 NA 0
#> 18 99 NA 0
#> 19 99 NA 0
#> 20 99 NA 0
Created on 2022-08-07 by the reprex package (v2.0.1.9000)