如何为列中的每个唯一值创建新的日期行?
How to create new date rows for each unique value in column?
我有一些数据看起来像这样。 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 月的新行,它们各自的 product/subproduct 值为 0.
您可以将 tidyr::complete()
与 nesting()
和 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 package (v2.0.0)
于 2021-07-07 创建
我有一些数据看起来像这样。 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 月的新行,它们各自的 product/subproduct 值为 0.
您可以将 tidyr::complete()
与 nesting()
和 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 package (v2.0.0)
于 2021-07-07 创建