加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

折叠/连接/聚合列到每个组中的单个逗号分隔的字符串

发布时间:2020-12-14 04:30:26 所属栏目:百科 来源:网络整理
导读:我想根据两个分组变量在数据框中聚合一列,并用逗号分隔各个值。 这里有一些数据: data - data.frame(A = c(rep(111,3),rep(222,3)),B = rep(1:2,C = c(5:10))data# A B C# 1 111 1 5# 2 111 2 6# 3 111 1 7# 4 222 2 8# 5 222 1 9# 6 222 2 10 “A”和“B
我想根据两个分组变量在数据框中聚合一列,并用逗号分隔各个值。

这里有一些数据:

data <- data.frame(A = c(rep(111,3),rep(222,3)),B = rep(1:2,C = c(5:10))
data
#     A B  C
# 1 111 1  5
# 2 111 2  6
# 3 111 1  7
# 4 222 2  8
# 5 222 1  9
# 6 222 2 10

“A”和“B”是分组变量,“C”是我要折叠成逗号分隔的字符串的变量。我努力了:

library(plyr)
ddply(data,.(A,B),summarise,test = list(C))

    A B  test
1 111 1  5,7
2 111 2     6
3 222 1     9
4 222 2 8,10

但是当我尝试将测试列转换为字符时,它变成如下:

ddply(data,test = as.character(list(C)))
#     A B     test
# 1 111 1  c(5,7)
# 2 111 2        6
# 3 222 1        9
# 4 222 2 c(8,10)

如何保留字符格式并用逗号分隔?例如,第1行应该只有“5,7”,而不是c(5,7)。

plyr尝试使用toString:
# plyr
library(plyr)
ddply(data,summarize,C = toString(C))

这里还有一些额外的替代方法也使用toString:

data.table

# alternative using data.table
library(data.table)
as.data.table(data)[,toString(C),by = list(A,B)]

聚合这不使用包:

# alternative using aggregate from the stats package in the core of R
aggregate(C ~.,data,toString)

sqldf

这里是使用SQL功能group_concat使用sqldf package的另一种方法:

library(sqldf)
sqldf("select A,B,group_concat(C) C from data group by A,B",method = "raw")

dplyr替代品:

library(dplyr)
data %>%
  group_by(A,B) %>%
  summarise(test = toString(C)) %>%
  ungroup()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读