【问题标题】:An efficient way to indicate multiple indicator variables per row with composite key? [duplicate]使用复合键指示每行多个指标变量的有效方法? [复制]
【发布时间】:2015-05-14 17:46:00
【问题描述】:

我的指标和值对象具有相互映射的复合键 有没有一种有效的方法将值聚合到指标对象中?

给定一个“空”指标数据框:

indicator <- data.frame(Id1=c(1,1,2,2,3,3,4,4), Id2=c(10,11,10,12,10,12,10,12),Ind_A=rep(0,8),Ind_B=rep(0,8))

    Id1    Id2 Ind_A Ind_B
1     1     10     0     0
2     1     11     0     0
3     2     10     0     0
4     2     12     0     0
5     3     10     0     0
6     3     12     0     0
7     4     10     0     0
8     4     12     0     0

和一个值的数据框:

values <- data.frame(Id1=c(1,1,1,2,2,3,3,4,4,4),Id2=c(10,10,11,10,12,10,12,10,10,12),Indicators=c('Ind_A','Ind_B','Ind_A','Ind_B','Ind_A','Ind_A','Ind_A','Ind_A','Ind_B','Ind_A'));

     Id1    Id2 Indicators
1      1     10      Ind_A
2      1     10      Ind_B
3      1     11      Ind_A
4      2     10      Ind_B
5      2     12      Ind_A
6      3     10      Ind_A
7      3     12      Ind_A
8      4     10      Ind_A
9      4     10      Ind_B
10     4     12      Ind_A

我想结束:

Id1     Id2   Ind_A    Ind_B
  1      10       1        1
  1      11       1        0
  2      10       0        1
  2      12       1        0
  3      10       1        0
  3      12       1        0
  4      10       1        1
  4      12       1        0

【问题讨论】:

    标签: r dataframe indicator


    【解决方案1】:

    您可以使用dcast 将“值”数据集从“长”格式转换为“宽”格式。

    library(reshape2)
    dcast(values, Id1+Id2~Indicators, value.var='Indicators', length)
    #    Id1 Id2 Ind_A Ind_B
    #1   1  10     1     1
    #2   1  11     1     0
    #3   2  10     0     1
    #4   2  12     1     0
    #5   3  10     1     0
    #6   3  12     1     0
    #7   4  10     1     1
    #8   4  12     1     0
    

    如上所示,您可能不需要创建第二个数据集,但如果您需要根据另一个数据集中的值更改一个数据集中的值,

    indicator$Ind_A <- (do.call(paste, c(indicator[1:2], 'Ind_A')) %in% 
                    do.call(paste, values))+0L
    indicator$Ind_B <- (do.call(paste, c(indicator[1:2], 'Ind_B')) %in% 
                    do.call(paste, values))+0L
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2015-02-19
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多