chriswang123456
chriswang123456

Reputation: 501

How to create new date rows for each unique value in column?

I have some data that looks like this. Jan-2019 to June-2021

date = seq(as.Date("2019/01/01"), by = "month", length.out = 29)

productB = rep("B",29)
productB = rep("B",29)
productA = rep("A",29)
productA = rep("A",29)

subproducts1=rep("1",29)
subproducts2=rep("2",29)
subproductsx=rep("x",29)
subproductsy=rep("y",29)

b1 <- c(rnorm(29,5))
b2 <- c(rnorm(29,5))
b3 <-c(rnorm(29,5))
b4 <- c(rnorm(29,5))


dfone <- data.frame("date"= rep(date,4),
                "product"= c(rep(productB,1),rep(productA,1)),
                "subproduct"= 
                  c(subproducts1,subproducts2,subproductsx,subproductsy),
                "actuals"= c(b1,b2,b3,b4))
dfone

I was wondering how I can add new dates up to 12-2022 for each unique subproduct with the product and subproduct intact but the value = 0 for new dates created? So my data ends at June 2021, I want new rows July 2021..... to Dec 2022 with their respective product/subproduct with value = 0.

Upvotes: 0

Views: 285

Answers (1)

AnilGoyal
AnilGoyal

Reputation: 26218

you may use tidyr::complete() with nesting() and fill = list() argument

library(tidyr)

dfone %>%
  complete(date = seq.Date(from = max(date), to = as.Date('2022-12-01'), by = 'month'), 
           nesting(product, subproduct), fill = list(actuals = 0))
#> # A tibble: 192 x 4
#>    date       product subproduct actuals
#>    <date>     <chr>   <chr>        <dbl>
#>  1 2021-05-01 A       2             5.12
#>  2 2021-05-01 A       y             4.33
#>  3 2021-05-01 B       1             4.50
#>  4 2021-05-01 B       x             7.01
#>  5 2021-06-01 A       2             0   
#>  6 2021-06-01 A       y             0   
#>  7 2021-06-01 B       1             0   
#>  8 2021-06-01 B       x             0   
#>  9 2021-07-01 A       2             0   
#> 10 2021-07-01 A       y             0   
#> # ... with 182 more rows

Created on 2021-07-07 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions