从几个字段到一个的聚合值 [英] aggregate values from several fields into one

查看:108
本文介绍了从几个字段到一个的聚合值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有以下数据框:

 对象类别
A 162
B 162
B 190
C 123
C 162
C 185
C 190
C 82
C 191
D 185

正如您所看到的那样,它们属于对象和类别。我想以逗号分隔列表总结每个对象的类别,以获取一个如下所示的数据框:

 对象类别
A 162
B 162,190
C 123,162,185,190,82,191
D 185
/ pre>

我该怎么做?

解决方案

使用您选择的任何聚合工具完成,我将使用 plyr 软件包和 paste()功能。这假设您的数据命名为 x

  library(plyr)
ddply(x,。(objects),summarize,categories = paste(categories,collapse =,))
#-----
对象类别
1 A 162
2 B 162,190
3 C 123,162,185,190,82,191
4 D 185


I have the following data frame in R:

objects   categories
   A       162
   B       162
   B       190
   C       123
   C       162
   C       185
   C       190
   C        82
   C       191
   D       185

As you see there are objects and the categories they belong to. I would like to sum up the categories of each object in comma separated list to get a data frame which would look like this:

 objects   categories
   A       162
   B       162, 190
   C       123, 162, 185, 190, 82, 191
   D       185

How could I do this?

解决方案

This can be done with any of the aggregation tools of your choice, I'll show an example using plyr package and paste() function. This assumes your data is named x:

library(plyr)
ddply(x, .(objects), summarize, categories = paste(categories, collapse = ","))
#-----
  objects             categories
1       A                    162
2       B                162,190
3       C 123,162,185,190,82,191
4       D                    185

这篇关于从几个字段到一个的聚合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆