如何为列中的每个唯一值创建新的日期行? [英] How to create new date rows for each unique value in column?

查看:15
本文介绍了如何为列中的每个唯一值创建新的日期行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据,如下所示。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
我想知道如何才能在产品和子产品完好无损的情况下为每个唯一的子产品添加直到2022年的新日期,但创建新日期的值=0?所以我的数据在2021年6月结束,我想要2021年7月的新行.....至2022年12月,其各自的产品/子产品的值=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创建

这篇关于如何为列中的每个唯一值创建新的日期行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆