Вы можете использовать complete
для добавления отсутствующих дат и fill
для сохранения state
и других столбцов.
library(dplyr)
library(tidyr)
df %>%
mutate(date = as.Date(date)) %>%
complete(county, date, fill = list(cases = 0, deaths = 0)) %>%
fill(everything(), .direction = "updown")
# county date state fips cases deaths
# <fct> <date> <fct> <int> <dbl> <dbl>
# 1 Cook 2020-01-21 Illinois 17031 0 0
# 2 Cook 2020-01-22 Illinois 17031 0 0
# 3 Cook 2020-01-23 Illinois 17031 0 0
# 4 Cook 2020-01-24 Illinois 17031 1 0
# 5 Cook 2020-01-25 Illinois 17031 1 0
# 6 Orange 2020-01-21 California 6059 0 0
# 7 Orange 2020-01-22 California 6059 0 0
# 8 Orange 2020-01-23 California 6059 0 0
# 9 Orange 2020-01-24 California 6059 0 0
#10 Orange 2020-01-25 California 6059 1 0
#11 Snohomish 2020-01-21 Washington 53061 1 0
#12 Snohomish 2020-01-22 Washington 53061 1 0
#13 Snohomish 2020-01-23 Washington 53061 1 0
#14 Snohomish 2020-01-24 Washington 53061 0 0
#15 Snohomish 2020-01-25 Washington 53061 1 0
data
df <- structure(list(date = structure(c(1L, 2L, 3L, 4L, 5L, 5L, 5L),
.Label = c("2020-01-21", "2020-01-22", "2020-01-23", "2020-01-24", "2020-01-25"),
class = "factor"),county = structure(c(3L, 3L, 3L, 1L, 3L, 1L, 2L),
.Label = c("Cook","Orange", "Snohomish"), class = "factor"),
state = structure(c(3L,3L, 3L, 2L, 3L, 2L, 1L),
.Label = c("California", "Illinois","Washington"), class = "factor"),
fips = c(53061L, 53061L, 53061L, 17031L, 53061L, 17031L, 6059L),
cases = c(1L, 1L, 1L, 1L, 1L, 1L, 1L), deaths = c(0L, 0L, 0L, 0L, 0L, 0L, 0L
)), class = "data.frame", row.names = c(NA, -7L))