Fill up rows of a data frame

I have this dataframe...

tibble(article=c("article a", "article a", "article a"), 
date=c(as_date("2020-07-04"), as_date("2020-07-12"), as_date("2020-07-29")), 
sales=c(54,52,46))

# A tibble: 3 x 3
  article   date       sales
  <chr>     <date>     <dbl>
1 article a 2020-07-04    54
2 article a 2020-07-12    52
3 article a 2020-07-29    46

... and want the date colum to be from "2020-07-01" to "2020-07-31" while the values for the article column remain the same and the values for the sales column are filled up with 0
Like:

# A tibble: 31 x 3
   article   date       sales
   <chr>     <date>     <dbl>
 1 article a 2020-07-01     0
 2 article a 2020-07-02     0
 3 article a 2020-07-03     0
 4 article a 2020-07-04    54
 5 article a 2020-07-05     0
 6 article a 2020-07-06     0
 7 article a 2020-07-07     0
 8 article a 2020-07-08     0
 9 article a 2020-07-09     0
10 article a 2020-07-10     0
# ... with 21 more rows

How would i do this?

Hello! This can be achieved by using the complete() function. I believe the following will work for you:

dat %>% 
  group_by(article) %>% 
  complete(date = seq.Date(from = as_date("2020-07-01"),
                           to = as_date("2020-07-31"),
                           by = "day"),
           fill = list(sales = 0))

See a similar question here

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.