Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df <- data.frame(signal = c(1,1,5,5,5,2,3,3,3,4,4,5,5,5,5,6,7,7,8,9,9,9,10),
- desired_outcome = c(NA, NA, 1, 1, 1, 5, 2, 2, 2, 3, 3, 4, 4,4,4,5,6,6,7,8,8,8,9))
- # outcome column has the expected result -
- signal desired_outcome
- 1 1 NA
- 2 1 NA
- 3 5 1
- 4 5 1
- 5 5 1
- 6 2 5
- 7 3 2
- 8 3 2
- 9 3 2
- 10 4 3
- 11 4 3
- 12 5 4
- 13 5 4
- 14 5 4
- 15 5 4
- 16 6 5
- 17 7 6
- 18 7 6
- 19 8 7
- 20 9 8
- 21 9 8
- 22 9 8
- 23 10 9
- with(rle(df$signal), rep(c(NA, head(values, -1)), lengths))
- # [1] NA NA 1 1 1 5 2 2 2 3 3 4 4 4 4 5 6 6 7 8 8 8 9
- library(dplyr)
- df %>%
- mutate(out = lag(signal)) %>%
- group_by(group = data.table::rleid(signal)) %>%
- mutate(out = first(out)) %>%
- ungroup() %>%
- select(-group)
- # A tibble: 23 x 2
- # signal out
- # <dbl> <dbl>
- # 1 1 NA
- # 2 1 NA
- # 3 5 1
- # 4 5 1
- # 5 5 1
- # 6 2 5
- # 7 3 2
- # 8 3 2
- # 9 3 2
- #10 4 3
- # … with 13 more rows
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement