I am trying to increase the columns for each group. Therefore, if there is a value, we increase it based on the value in front of it, otherwise we will leave it.
So, for example, it will go from df to dfb.
df <- data.frame(group = c("A", "A", "B", "B", "B", "C", "C", "C", "D", "D"), num = c(1, NA, NA, 8, NA, 5, NA, NA, 10, NA)) dfb <- data.frame(group = c("A", "A", "B", "B", "B", "C", "C", "C", "D", "D"), num = c(1, 2, NA, 8, 9, 5, 6, 7, 10, 11)) > df group num 1 A 1 2 A NA 3 B NA 4 B 8 5 B NA 6 C 5 7 C NA 8 C NA 9 D 10 10 D NA > dfb group num 1 A 1 2 A 2 3 B NA 4 B 8 5 B 9 6 C 5 7 C 6 8 C 7 9 D 10 10 D 11
My best attempt was this, but it did not work
dfc <- df %>% mutate(num = ifelse(is.na(num),lag(num) + 1, num))
Deleted my previous question because my problem was previously poorly defined. Thanks for the help!