0

I have a dataframe like this:

ID  Value
1   C
2   B
3   B
4   A
5   C
6   B
7   B
8   A
9   C
10  B
11  B
12  A
13  C
14  B
15  B

I would like to get a new table with all ID with the same value, like this:

 IDs                Value
1,5,9,13            C
2,3,6,7,10,11,14,15 B
4,8,12              A

I don't mind if the are coma separated or not.

Thanks

S Rivero
  • 708
  • 5
  • 14

1 Answers1

2

We can use aggregate to paste the 'ID's for each unique 'Value'

aggregate(ID~Value, df1, FUN= toString)
# Value                         ID
#1     A                   4, 8, 12
#2     B 2, 3, 6, 7, 10, 11, 14, 15
#3     C                1, 5, 9, 13

If we need a list column, use c as FUN

aggregate(ID~Value, df1, FUN = c)

The same can be done using other packages such as data.table

library(data.table)
setDT(df1)[, .(Values =toString(Value)), by = ID]

or dplyr

library(dplyr)
df1 %>%
    group_by(ID) %>%
    summarise(Values = toString(Value))
akrun
  • 874,273
  • 37
  • 540
  • 662