Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. 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),
  2. 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))
  3.  
  4. # outcome column has the expected result -
  5. signal desired_outcome
  6. 1 1 NA
  7. 2 1 NA
  8. 3 5 1
  9. 4 5 1
  10. 5 5 1
  11. 6 2 5
  12. 7 3 2
  13. 8 3 2
  14. 9 3 2
  15. 10 4 3
  16. 11 4 3
  17. 12 5 4
  18. 13 5 4
  19. 14 5 4
  20. 15 5 4
  21. 16 6 5
  22. 17 7 6
  23. 18 7 6
  24. 19 8 7
  25. 20 9 8
  26. 21 9 8
  27. 22 9 8
  28. 23 10 9
  29.  
  30. with(rle(df$signal), rep(c(NA, head(values, -1)), lengths))
  31. # [1] NA NA 1 1 1 5 2 2 2 3 3 4 4 4 4 5 6 6 7 8 8 8 9
  32.  
  33. library(dplyr)
  34.  
  35. df %>%
  36. mutate(out = lag(signal)) %>%
  37. group_by(group = data.table::rleid(signal)) %>%
  38. mutate(out = first(out)) %>%
  39. ungroup() %>%
  40. select(-group)
  41.  
  42.  
  43. # A tibble: 23 x 2
  44. # signal out
  45. # <dbl> <dbl>
  46. # 1 1 NA
  47. # 2 1 NA
  48. # 3 5 1
  49. # 4 5 1
  50. # 5 5 1
  51. # 6 2 5
  52. # 7 3 2
  53. # 8 3 2
  54. # 9 3 2
  55. #10 4 3
  56. # … with 13 more rows
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement