dcast并汇总到r中的长度

时间:2018-07-29 05:40:55

标签: r

我在R中有以下数据框

   ID   credit_active    credit_currency      credit_type
   1    Active           Dollars              Home
   1    Closed           Dollars              Home
   1    Active           Euro                 Home
   2    Active           Dollars              Home
   2    Closed           Dollars              Home
   2    Active           Euro                 Home

我想要以下格式的数据

   ID     Active    Closed     Dollars     Euro     Home
   1      2         1          2           1        3
   2      2         1          2           1        3

我正在使用dcast函数执行上述操作

  dcast_bureau <- dcast(setDT(bureau),ID~ credit_active + credit_currency + credit_type,
                  value.var = c("credit_active ","credit_currency ","credit_type")
                  ,fun.aggregate = length)       

但是它没有给我我想要的格式。 如何在r中做到这一点?

1 个答案:

答案 0 :(得分:4)

我们需要meltdcast。如果存在重复的元素,则默认情况下,fun.aggregatelength

dcast(melt(setDT(bureau), id.var = 'ID'), ID ~ value)
#    ID Active Closed Dollars Euro Home
#1:  1      2      1       2    1    3
#2:  2      2      1       2    1    3

reshape2中,有一个方便的包装器recastmelt + dcast),它将使其更紧凑

library(reshape2)
recast(bureau, id.var = 'ID', ID ~ value)