Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- code data
- 1 A 1
- 2 2
- 3 3
- 4 4
- 5 5
- 6 6
- 7 7
- 8 8
- 9 9
- 10 10
- 11 B 11
- 12 12
- 13 13
- 14 14
- 15 15
- 16 C 16
- 17 17
- 18 18
- 19 19
- 20 20
- code data
- 1 A 1
- 2 A 2
- 3 A 3
- 4 A 4
- 5 A 5
- 6 A 6
- 7 A 7
- 8 A 8
- 9 A 9
- 10 A 10
- 11 B 11
- 12 B 12
- 13 B 13
- 14 B 14
- 15 B 15
- 16 C 16
- 17 C 17
- 18 C 18
- 19 C 19
- 20 C 20
- # Create mock data frame
- df <- data.frame(code = c("A", rep("", 9),
- "B", rep("", 4),
- "C", rep("", 4)),
- data = 1:20)
- # For loop over rows (BAD!)
- for (i in seq(2, nrow(df))) {
- df[i,]$code <- ifelse(df[i,]$code == "", df[i-1,]$code, df[i, ]$code)
- }
- df %>%
- mutate(code = na_if(code,"")) %>%
- fill(code)
- code data
- 1 A 1
- 2 A 2
- 3 A 3
- 4 A 4
- 5 A 5
- 6 A 6
- 7 A 7
- 8 A 8
- 9 A 9
- 10 A 10
- 11 B 11
- 12 B 12
- 13 B 13
- 14 B 14
- 15 B 15
- 16 C 16
- 17 C 17
- 18 C 18
- 19 C 19
- 20 C 20
Add Comment
Please, Sign In to add comment