根据某些列扩展数据框

问题描述 投票:0回答:1

我有以下形状的数据:

old<-
data.frame(date = c("04/01/2022", "05/01/2022", "07/01/2022", "04/01/2022", "06/01/2022","07/01/2022"), 
           type = c(rep("x", 3), rep("y",3)),
           name = c("t", "p", "k", "t", "p", "L"), 
           value = c(10,20,30, 9, 5, 8))

我不确定使用什么术语,但我想“扩展”“旧”数据集,使其看起来像“新”数据集。

new <- 
  data.frame(
    date = c(rep("04/01/2022",4),rep("05/01/2022",4), rep("06/01/2022",4), rep("07/01/2022",4) ),
    type = c(rep("x", 16), rep("y", 16)), 
    name = c("t", "p", "k","L"), 
    value = c("10", "0", "0", "0", "0", "20", rep("0",8), "30" ,"0",
              "0", rep("0",8), "5", rep("0",5), "8")
  )

“扩展”方法如下:

  • 我的数据仅包含那些我有值的日子的观察结果。
  • 我想每天重复类型和名称列,以便每天我都有一个包含所有类型和所有名称的数据框。
  • 对于那些我在“旧”中没有观察到的日期/类型/名称,然后用 0 零填充。

请注意,这不是一个简单的更宽的枢轴,因为我需要添加观察结果。

生成的 data.frame 因此是一个 N.dateN.typeN.name 矩阵。

r dplyr data.table
1个回答
0
投票
library(data.table)
setDT(old)
new2 <- 
  old[CJ(date, type, name, unique=TRUE), on = c("date", "type", "name")
      ][, value := replace(value, is.na(value), 0)][]
© www.soinside.com 2019 - 2024. All rights reserved.