gpt4 book ai didi

R:合并同一数据表中的行,连接某些列

转载 作者:行者123 更新时间:2023-12-04 03:22:32 25 4
gpt4 key购买 nike

我在 R 中有我的数据表。我想合并具有相同 customerID 的行,然后连接其他合并列的元素。

我想从这个开始:

   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函数应该可以帮助您找到解决方案:

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) 的内容。首先将它们转换为字符,然后:
aggregate(dat[-3], by=list(dat$customerID), c)
# Group.1 title author
# 1 1 title1, title3 author1, author3
# 2 2 title2 author2

关于R:合并同一数据表中的行,连接某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11364992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com