1

I have a dataframe called flu that is a count of case(n) by group per week.

flu <- structure(list(isoweek = c(1, 1, 2, 2, 3, 3, 4, 5, 5), group = c("fluA", 
"fluB", "fluA", "fluB", "fluA", "fluB", "fluA", "fluA", "fluB"
), n = c(5, 6, 3, 5, 12, 14, 6, 23, 25)), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), spec = structure(list(
    cols = list(isoweek = structure(list(), class = c("collector_double", 
    "collector")), group = structure(list(), class = c("collector_character", 
    "collector")), n = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

In the data set there are some rows where zero cases are not reported in the data so there are no NA values to work with. I have identified a fix for this to fill down missing weeks with zeros.

flu %>% complete(isoweek, nesting(group), fill = list(n = 0))

My problem is that this only works for the weeks of data reported. For example, at weeks 6, 7, 8 etc if there are no cases reported I have no data.

How can I extend this fill down process to extend the data frame with zeros for isoweeks 6 to 10 (for example) and have a corresponding fluA and fluB for each week with a zero value for each isoweek/group pair?

John
  • 41,131
  • 31
  • 82
  • 106

1 Answers1

1

You can expand multiple columns in complete. Let's say if you need data till week 8, you can do :

tidyr::complete(flu, isoweek = 1:8, group, fill = list(n = 0))

# A tibble: 16 x 3
#   isoweek group     n
#     <dbl> <chr> <dbl>
# 1       1 fluA      5
# 2       1 fluB      6
# 3       2 fluA      3
# 4       2 fluB      5
# 5       3 fluA     12
# 6       3 fluB     14
# 7       4 fluA      6
# 8       4 fluB      0
# 9       5 fluA     23
#10       5 fluB     25
#11       6 fluA      0
#12       6 fluB      0
#13       7 fluA      0
#14       7 fluB      0
#15       8 fluA      0
#16       8 fluB      0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213