【问题标题】:How to impute values for a specific condition?如何估算特定条件的值?
【发布时间】:2015-05-08 02:49:04
【问题描述】:

我的问题可能有两个方面:对于特定条件和特定组,我想估算两组值。

让我用数据解释一下:

df <- data.frame(id = c(rep("a",6),rep("b",6),rep("c",7)), 
                 num = c(rep(1:6, 2),rep(1:7)), 
                 status = c(rep("good",6),rep("bad",6),rep("bad",7)), value = c(100))

> df
   id num status value
1   a 1   good   100
2   a 2   good   100
3   a 3   good   100
4   a 4   good   100
5   a 5   good   100
6   a 6   good   100
7   b 1    bad   100
8   b 2    bad   100
9   b 3    bad   100
10  b 4    bad   100
11  b 5    bad   100
12  b 6    bad   100
13  c 1    bad   100
14  c 2    bad   100
15  c 3    bad   100
16  c 4    bad   100
17  c 5    bad   100
18  c 6    bad   100
19  c 7    bad   100
> 

如果状态 = bad,则将 num 扩展为 50,并将 0 归入值中。

所以对于id 'b' 和 'c',我会产生 44 和 43 个额外的行,分别在num 中按顺序编号。这些新行的value 将是0...

非常感谢任何和所有帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以生成“构建”数据,然后将其堆叠:

    require(data.table)
    DT0 <- data.table(df)
    
    DT <- rbind(
      DT0,
      DT0[status=="bad",list(num=.N:49+1L,status="bad",value=0),by=id]
    )[order(id,num)]
    

    您必须先安装 data.table 软件包。

    【讨论】:

    • 感谢@Frank - 这是一个很棒的解决方案!
    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 2020-09-28
    • 2022-06-22
    • 2018-09-23
    • 1970-01-01
    • 2019-12-28
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多