按组对值进行排序和连接 [英] Sort and concatenate values by group
本文介绍了按组对值进行排序和连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个组和名称列表,如下面的 DF 所示.我希望按字母顺序排列这个列表,并连接由逗号分隔的每个名称,如下面的 DF2 所示.我以为这很简单,但事实证明它比预期的更具挑战性!
I've got a list of Groups and Names, as seen in DF below. I'm looking to arrange this list alphabetically and concatenate each name separated by a comma, as seen in DF2 below. I thought this would be simple, but it is proving to be more challenging than expected!
DF <- tibble::data_frame(
Group = c(1, 1, 1, 2, 2, 3, 3, 3),
Name = c("A", "B", "C", "B", "A", "B", "C", "A"))
DF2 <- tibble::data_frame(
Group = c(1, 2, 3),
Name = c("A, B, C", "A, B", "A, B, C"))
对于解决这个问题的任何帮助,无论是否有 dplyr 管道,我都会感谢每个组列出的未知数量的名称.
I'd appreciate any help in solving this to account for an unknown number of names listed per group, either with or without a dplyr pipeline.
谢谢!
推荐答案
我们可以使用data.table
library(data.table)
setDT(DF)[order(Name), .(Comb = toString(Name)) , by = Group]
这篇关于按组对值进行排序和连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文