【问题标题】:Data.table: Add rows for missing combinations of 2 factors without losing associated descriptive factorsData.table:为缺少 2 个因素的组合添加行,而不会丢失相关的描述性因素
【发布时间】:2016-03-03 16:00:11
【问题描述】:

我有一个包含多个因子的数据表,例如:

dt <- data.table(station=c(1,1,2,2,3), station.type=c("X","X","Y","Y","Y"), stage=c("A","B","A","B","A"), value=10:14)

   station station.type stage value
1:       1            X     A    10
2:       1            X     B    11
3:       2            Y     A    12
4:       2            Y     B    13
5:       3            Y     A    14

每个站点都与一个类型相关联(我的实际数据有超过 50 个站点和 10 种类型)。在该示例中,缺少组合站 3/阶段 B。我想为缺少的组合添加行,同时保留与车站关联的类型。

我从 Matt Dowle 对这个问题的回答开始: Fastest way to add rows for missing values in a data.frame?

setkey(dt, station, stage)
dt[CJ(station, stage, unique=TRUE)]

   station station.type stage value
1:       1            X     A    10
2:       1            X     B    11
3:       2            Y     A    12
4:       2            Y     B    13
5:       3            Y     A    14
6:       3           NA     B    NA

但是我必须与原始数据表再次合并以填写每个站的类型。

有没有办法在一行中完成所有操作 - 例如:

dt[CJ(cbind(station, station.type), stage, unique=TRUE)]

(当然这不起作用,因为 CJ 将向量作为参数)

【问题讨论】:

  • 也许是dt[, .SD[.(stage=c("A", "B")), on="stage"], by=.(station, station.type)]?
  • 或使用zoo 包中的na.locf 函数:dt[CJ(station, stage, unique=TRUE)][, station.type := na.locf(station.type)]
  • @Arun,谢谢,你能把这个作为答案发给我吗?

标签: r data.table


【解决方案1】:

这是一种方法:

dt[, .SD[.(stage=c("A", "B")), on="stage"], by=.(station, station.type)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多