Мы можем использовать complete
из tidyr
library(tidyr)
library(dplyr)
df1 %>%
complete(Person, month = 1:12, Year, fill = list(Quantity = 0)) %>%
arrange(Person, Year)
# A tibble: 48 x 4
# Person month Year Quantity
# <chr> <int> <int> <dbl>
# 1 A 1 2018 0
# 2 A 2 2018 900
# 3 A 3 2018 0
# 4 A 4 2018 600
# 5 A 5 2018 0
# 6 A 6 2018 0
# 7 A 7 2018 0
# 8 A 8 2018 0
# 9 A 9 2018 300
#10 A 10 2018 0
# … with 38 more rows
### data
df1 <- structure(list(Person = c("A", "A", "A", "A", "B", "B", "B"),
month = c(2L, 4L, 9L, 4L, 6L, 1L, 9L), Year = c(2018L, 2018L,
2018L, 2019L, 2018L, 2019L, 2019L), Quantity = c(900L, 600L,
300L, 40L, 56L, 10L, 20L)), class = "data.frame", row.names = c(NA,
-7L))