I have a dataset as follows:
col1    col2
a        1
a        2
b        1
b        3
c        4
I want the output as follows:
col1    col2
a        1,2
b        1,3
c        4
How is it possible in R?
I have a dataset as follows:
col1    col2
a        1
a        2
b        1
b        3
c        4
I want the output as follows:
col1    col2
a        1,2
b        1,3
c        4
How is it possible in R?
 
    
    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))
