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
  • 61,039
  • 13
  • 131
  • 152
kputschko
  • 642
  • 1
  • 7
  • 18

2 Answers2

3

We can use data.table

library(data.table)
setDT(DF)[order(Name), .(Comb = toString(Name)) , by = Group]
akrun
  • 789,025
  • 32
  • 460
  • 575
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
  • 11,865
  • 5
  • 27
  • 49