How to concatenate text by group in R

To concatenate, you can use R base functions paste and paste0 that are almost the same. The only difference is in the separator argument. In this situation, we will use the collapse argument that will separate all the text within a group when concatenated.

It is easy to implement that with the help of dplyr package.

To concatenate by group in R you can use a paste with a collapse argument within mutate to return all rows in the dataset with results in a separate column or summarise to return only group values with results.

require(dplyr)

group_and_concat <- starwars %>%
  select(name, species, homeworld) %>% 
  group_by(species) %>%
  mutate(all_names = paste(name, collapse = " | "))

require(dplyr)

group_and_concat <- starwars %>%
  group_by(species) %>%
  summarise(all_names = paste(name, collapse = " | "))

If you want to know how to reflow your code or other useful RStudio tips and tricks, take a look at this post.

For a quick and easy way to copy results from R to Excel, take a look at this solution.




Posted

in

Comments

3 responses to “How to concatenate text by group in R”

  1. BB

    this does not work for me. The grouping does not work – it simply gives me one row of concatenated values. Any idea why? It is completely ignoring the group by.

    group_and_concat %
    group_by(ID) %>%
    summarise(all_names = paste(these_words, collapse = ” | “))

    1. Elsa

      I believe you’ve loaded plyr after dplyr, which is why you are getting an overall summary instead of a grouped summary. Remove plyr and try again and you get the grouped summary.

  2. Joe

    This did exactly what I needed, thank you!

Leave a Reply

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