1

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"))

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.

Thanks!

Henrik
  • 65,555
  • 14
  • 143
  • 159
kputschko
  • 766
  • 1
  • 7
  • 21

2 Answers2

3

We can use data.table

library(data.table)
setDT(DF)[order(Name), .(Comb = toString(Name)) , by = Group]
akrun
  • 874,273
  • 37
  • 540
  • 662
3

In base R:

aggregate(Name~Group, DF, function(x) paste0(sort(x), collapse = ","))

#  Group  Name
#1     1 A,B,C
#2     2   A,B
#3     3 A,B,C
989
  • 12,579
  • 5
  • 31
  • 53