我在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中做到呢?
发布于 2018-07-29 05:43:14
我们需要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)https://stackoverflow.com/questions/51577573
复制相似问题