We can group by 'col1' and paste
the 'col2' with collapse=','
option. A convenient wrapper would be toString
. This can be done with any of the aggregate by group functions. For example, with data.table
, we convert 'data.frame' to 'data.table' (setDT(df1)
) and use the logic as described above
library(data.table)
setDT(df1)[, list(col2 = toString(col2)), by = col1]
Or with aggregate
from base R
aggregate(col2~col1, df1, FUN=toString)
If you need a list
output for 'col2'
aggregate(col2~col1, df1, FUN=I)
Or using dplyr
library(dplyr)
df1 %>%
group_by(col1) %>%
summarise(col2= toString(col2))