r - 如何为列中的每个唯一值创建新的日期行?
问题描述
我有一些看起来像这样的数据。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。
解决方案
你可以使用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 )
推荐阅读
- arrays - 解决这个完成块
- mongodb - 如何在数组中使用 mongoDB 中的 dateFromString
- python - Scrapy 导入错误:没有名为 Scrapy 的模块
- math - 在 Jupyter Notebook 中用 Markdown 编写的数学符号在 GitHub 上呈现不一致
- node.js - 在控制台中将 NodeJS / MongoDB 查询输出到 String Runnable
- gradle - 如何强制更改gradle中mudule的依赖关系
- react-native-android - react native run android不起作用,并且无法安装应用程序
- angular - PrimeNG p-tree 过滤器问题
- java - 不允许在数组列表中重复对象
- android - 如何在onDatachanged中存储arraylist并在android外部返回