R:合并同一数据表中的行,并串联某些列 [英] R: Merge of rows in same data table, concatenating certain columns
问题描述
我在R中有我的数据表.我想合并具有相同customerID
的行,然后将其他合并列的元素串联起来.
I have my data table in R. I want to merge rows which have an identical customerID
, and then concatenate the elements of other merged columns.
我想从这里出发:
title author customerID
1 title1 author1 1
2 title2 author2 2
3 title3 author3 1
对此:
title author Group.1
1 title1, title3 author1, author3 1
2 title2 author2 2
推荐答案
aggregate
函数应该可以帮助您找到解决方案:
The aggregate
function should help you in finding a solution:
dat = data.frame(title = c("title1", "title2", "title3"),
author = c("author1", "author2", "author3"),
customerID = c(1, 2, 1))
aggregate(dat[-3], by=list(dat$customerID), c)
# Group.1 title author
# 1 1 1, 3 1, 3
# 2 2 2 2
或者,只需确保在创建数据框时添加stringsAsFactors = FALSE
,就可以了.如果您的数据已经被分解,则可以使用dat[c(1, 2)] = apply(dat[-3], 2, as.character)
之类的东西先将其转换为字符,然后:
Or, just make sure you add stringsAsFactors = FALSE
when you are creating your data frame and you're pretty much good to go. If your data are already factored, you can use something like dat[c(1, 2)] = apply(dat[-3], 2, as.character)
to convert them to character first, then:
aggregate(dat[-3], by=list(dat$customerID), c)
# Group.1 title author
# 1 1 title1, title3 author1, author3
# 2 2 title2 author2
这篇关于R:合并同一数据表中的行,并串联某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!