R使用dcast,melt和concatenation来重塑数据框架

时间:2016-08-19 05:30:30

标签: r reshape reshape2 dcast

我的数据框如下:

mydf <- data.frame(Term = c('dog','cat','lion','tiger','pigeon','vulture'), Category = c('pet','pet','wild','wild','pet','wild'),
    Count = c(12,14,19,7,11,10), Rate = c(0.4,0.7,0.3,0.6,0.1,0.8), Brand = c('GS','GS','MN','MN','PG','MN')    ) 

导致数据框:

     Term Category Count Rate Brand
1     dog      pet    12  0.4    GS
2     cat      pet    14  0.7    GS
3    lion     wild    19  0.3    MN
4   tiger     wild     7  0.6    MN
5  pigeon      pet    11  0.1    PG
6 vulture     wild    10  0.8    MN

我希望将此数据框转换为以下resultDF

Category         pet              wild              
Term             dog,cat,pigeon   lion,tiger,vulture
Countlessthan13  dog,pigeon       tiger,vulture     
Ratemorethan0.5  cat              tiger,vulture     
Brand            GS,PG            MN                

行标题表示像Countlessthan13这样的操作意味着Count&lt;将13应用于术语然后分组。 另请注意,品牌名称是独一无二的,并没有重新评估。

我尝试过dcast并融化......但没有得到理想的结果。

1 个答案:

答案 0 :(得分:3)

我们可以使用data.table执行此操作。将“data.frame”转换为“data.table”(setDT(mydf)),按“类别”分组,按paste {Term}的unique值创建一些汇总列,其中“计数”小于13或“费率”大于0.5,以及paste“品牌”的unique元素。

library(data.table)
dt <- setDT(mydf)[, .(Term = paste(unique(Term), collapse=","),
                      Countlesstthan13 =  paste(unique(Term[Count < 13]), collapse=","),

                      Ratemorethan0.5 = paste(unique(Term[Rate > 0.5]), collapse=","), 
                      Brand = paste(unique(Brand), collapse=",")), by = Category]

从汇总数据集('dt'),我们melt到'long'格式,将'id.var'指定为'Category',然后dcast将其恢复为'wide'格式

dcast(melt(dt, id.var = "Category", variable.name = "category"),
                            category ~Category, value.var = "value")
#           category            pet               wild
#1:             Term dog,cat,pigeon lion,tiger,vulture
#2: Countlesstthan13     dog,pigeon      tiger,vulture
#3:  Ratemorethan0.5            cat      tiger,vulture
#4:            Brand          GS,PG                 MN