1

I have a transient amnesia. I recall there's an R function that allows to get list of elements in a group after aggregating. To be clearer, from here:

DT<-data.table(x=rep(c("cool","uncool"),each=3),group=c(1,1,2,2,3,3))

That gives:

    x    group
   cool     1
   cool     1
   cool     2
 uncool     2
 uncool     3
 uncool     3

I would like to end up with:

 x      group
cool    1,1,2
uncool  2,3,3

I used that function in the past, but can't remember now. Anyone can help? Thank you

2 Answers2

2

Option 1

Using aggregate

aggregate(group ~ x, DT, toString)
#       x   group
#1   cool 1, 1, 2
#2 uncool 2, 3, 3

or

aggregate(group ~ x, DT, paste0, collapse = ",")
#       x group
#1   cool 1,1,2
#2 uncool 2,3,3

Option 2

The data.table way

DT[, .(group = toString(group)), by = x]
#    x       group
#1:   cool 1, 1, 2
#2: uncool 2, 3, 3

or

DT[, .(group = paste0(group, collapse = ",")), by = x]
#        x group
#1:   cool 1,1,2
#2: uncool 2,3,3
Maurits Evers
  • 45,165
  • 4
  • 35
  • 59
1

Here is an option using tidyverse

library(tidyverse)
DT %>%
  group_by(x) %>%
  summarise(group = toString(group))
akrun
  • 789,025
  • 32
  • 460
  • 575