You could use complete
to fill the missing days.
library(dplyr)
library(tidyr)
df1 <- df %>%
mutate(DAY1 = DAY) %>%
complete(ID, DAY, fill = list(DAY1 = -99)) %>%
select(ID, DAY = DAY1)
df1
# ID DAY
# <int> <dbl>
# 1 1 1
# 2 1 2
# 3 1 3
# 4 1 4
# 5 2 1
# 6 2 -99
# 7 2 3
# 8 2 4
# 9 3 1
#10 3 -99
#11 3 3
#12 3 -99
For the updated data we can try to add day
by group :
df1 <- df %>%
group_by(id) %>%
complete(day = min(day):max(day), fill = list(amount = -99))
df1
data
df <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L), DAY = c(1L,
2L, 3L, 4L, 1L, 3L, 4L, 1L, 3L)), class = "data.frame", row.names = c(NA, -9L))
CLICK HERE to find out more related problems solutions.