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

Create comma-separated list of unqiue values in dplyr

I have the following dataframe:

df<-data.frame(city=c("Berlin","Berlin","Frankfurt","Frankfurt","Frankfurt"),
                          item=c("A","B","A","D","E"))
df
#>        city item
#> 1    Berlin    A
#> 2    Berlin    B
#> 3 Frankfurt    A
#> 4 Frankfurt    D
#> 5 Frankfurt    E

I would like to achieve the following:

#>        city   items
#> 1    Berlin     A,B
#> 2 Frankfurt   A,D,E

How do I do that preferably with dplyr?

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 :

A possible solution:

library(dplyr)

df %>% 
  group_by(city) %>% 
  summarise(item = str_c(item, collapse = ", "))

#> # A tibble: 2 x 2
#>   city      item   
#>   <chr>     <chr>  
#> 1 Berlin    A, B   
#> 2 Frankfurt A, D, E
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