首页 > 解决方案 > 如何为列中的每个唯一值创建新的日期行?

问题描述

我有一些看起来像这样的数据。2019 年 1 月至 2021 年 6 月

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

我想知道如何为每个独特的子产品添加最多 12-2022 的新日期,并且产品和子产品完好无损,但创建的新日期的值 = 0?所以我的数据在 2021 年 6 月结束,我想要 2021 年 7 月到 2022 年 12 月的新行,它们各自的产品/子产品的值 = 0。

标签: rloopsdplyrdata-manipulation

解决方案


你可以使用tidyr::complete()withnesting()fill = list()参数

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

reprex 包于 2021-07-07 创建 (v2.0.0 )


推荐阅读