Concatenate strings by group with dplyr in R

Hello friends! today we’ll be learning how to Concatenate strings by group with dplyr in R. I’ll be using iris data available in R

Data

Sepal.LengthSepal.WidthPetal.LengthPetal.WidthSpecies
5.13.51.40.2setosa
4.931.40.2setosa
4.73.21.30.2setosa
4.63.11.50.2setosa
53.61.40.2setosa
5.43.91.70.4setosa
4.63.41.40.3setosa

Code

So the key used is Species to group by and Sepal.Length is concatenated with “,”

library(dplyr)  
df <- iris %>% 
select(Species,Sepal.Length) %>% 
group_by(Species) %>% 
mutate(Grp = paste0(Sepal.Length, collapse = ",")) %>% 
distinct(Species, Grp, .keep_all = TRUE) 
df

Keep visiting Analytics Tuts for more tutorials.

Thanks for reading! Comment your suggestions and queries


Leave a Reply

Your email address will not be published. Required fields are marked *