Guest User

Untitled

a guest
Jul 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. code data
  2. 1 A 1
  3. 2 2
  4. 3 3
  5. 4 4
  6. 5 5
  7. 6 6
  8. 7 7
  9. 8 8
  10. 9 9
  11. 10 10
  12. 11 B 11
  13. 12 12
  14. 13 13
  15. 14 14
  16. 15 15
  17. 16 C 16
  18. 17 17
  19. 18 18
  20. 19 19
  21. 20 20
  22.  
  23. code data
  24. 1 A 1
  25. 2 A 2
  26. 3 A 3
  27. 4 A 4
  28. 5 A 5
  29. 6 A 6
  30. 7 A 7
  31. 8 A 8
  32. 9 A 9
  33. 10 A 10
  34. 11 B 11
  35. 12 B 12
  36. 13 B 13
  37. 14 B 14
  38. 15 B 15
  39. 16 C 16
  40. 17 C 17
  41. 18 C 18
  42. 19 C 19
  43. 20 C 20
  44.  
  45. # Create mock data frame
  46. df <- data.frame(code = c("A", rep("", 9),
  47. "B", rep("", 4),
  48. "C", rep("", 4)),
  49. data = 1:20)
  50.  
  51. # For loop over rows (BAD!)
  52. for (i in seq(2, nrow(df))) {
  53. df[i,]$code <- ifelse(df[i,]$code == "", df[i-1,]$code, df[i, ]$code)
  54. }
  55.  
  56. df %>%
  57. mutate(code = na_if(code,"")) %>%
  58. fill(code)
  59.  
  60. code data
  61. 1 A 1
  62. 2 A 2
  63. 3 A 3
  64. 4 A 4
  65. 5 A 5
  66. 6 A 6
  67. 7 A 7
  68. 8 A 8
  69. 9 A 9
  70. 10 A 10
  71. 11 B 11
  72. 12 B 12
  73. 13 B 13
  74. 14 B 14
  75. 15 B 15
  76. 16 C 16
  77. 17 C 17
  78. 18 C 18
  79. 19 C 19
  80. 20 C 20
Add Comment
Please, Sign In to add comment