通过分组行来转换数据帧 [英] Transform dataframe by grouping row
本文介绍了通过分组行来转换数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
d1 < - data.frame(Gender = c('M','M','M','M','F','F','F' F'),年龄= c(15,38,17,35,26,24,20,26))
如果可能的话,我想改造它看起来像这样:
And I'd like to transform it to look like this,if possible:
Gender Age
M 15, 38, 17, 35
F 26, 24, 20, 26
推荐答案
p>您可以按性别分组,然后合并到您的字符串中,最后结合:
You can split by gender, then combine into your string, and finally combine:
spl = split(d1, d1$Gender)
spl = lapply(spl, function(x) data.frame(Gender=x$Gender[1],
Age=paste(x$Age, collapse=", ")))
result = do.call(rbind, spl)
这篇关于通过分组行来转换数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文