Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make column with lists of characters that match a second column in R

I have a data frame in R with 2 columns, each of which has repeat values.

df <- data.frame(item  = c("X", "Y", "Z", "X", "Z"),
                  label = c("ABC", "DEF", "DEF", "GHI", "ABC"))

 item label
1    X   ABC
2    Y   DEF
3    Z   DEF
4    X   GHI
5    Z   ABC

I’d like to transform it so that I have a unique row for each label and a column that lists all the items that match it separated by commas. So something like this:

 label items
1   ABC  X, Z
2   DEF  Y, Z
3   GHI     X

I’ve tried using spread and aggregate, but I haven’t been able to land on something that works. Does anyone have suggestions? Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could use toString:

library(dplyr)

df %>% 
  group_by(label) %>% 
  summarise(item = toString(item))
  label item 
  <chr> <chr>
1 ABC   X, Z 
2 DEF   Y, Z 
3 GHI   X    
``´
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading