繁体   English   中英

R使用dcast,melt和concatenation重塑数据帧

[英]R using dcast,melt and concatenation to reshape data frame

我有一个数据框,如下所示:

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 <13应用于术语,然后进行分组。 另请注意,品牌名称是唯一的而不是真实的。

我已经尝试过dcast并融化了...但是没有得到想要的结果。

我们可以使用data.table做到这data.table 将'data.frame'转换为'data.table'( setDT(mydf) ),按'Category'分组,通过paste 'Term'的uniquesetDT(mydf)小于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')中,我们通过将'id.var'指定为'Category' melt为'long'格式,然后dcastdcast为'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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM