aggregate values from several fields into one

吃可爱长大的小学妹 提交于 2019-12-01 12:15:38

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
aggregate(categories~objects,data=x,FUN=paste)
  objects                  categories
1       A                         162
2       B                    162, 190
3       C 123, 162, 185, 190, 82, 191
4       D                         185

As the title of your question implies, use aggregate:

aggregate(list(categories=df$categories), by=list(objects=df$objects), c)
#   objects                  categories
# 1       A                         162
# 2       B                    162, 190
# 3       C 123, 162, 185, 190, 82, 191
# 4       D                         185

aggregate If DF is your data frame then try this:

aggregate(categories ~ objects, DF, function(x) toString(unique(x)))

sqldf With sqldf this works:

library(sqldf)
sqldf("select objects, group_concat(distinct categories) as categories
  from DF group by objects")

A data.table solution

library(data.table)
DT <- as.data.table(DF)
DT[,list(categories = list(categories)), by = objects]

##    objects             categories
## 1:       A                    162
## 2:       B                162,190
## 3:       C 123,162,185,190,82,191
## 4:       D                    185
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!