我在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中做到这一点?
答案 0 :(得分:4)
我们需要melt
和dcast
。如果存在重复的元素,则默认情况下,fun.aggregate
是length
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
中,有一个方便的包装器recast
(melt
+ dcast
),它将使其更紧凑
library(reshape2)
recast(bureau, id.var = 'ID', ID ~ value)