Search code examples
rdistinctplyr

r - Combine the distinct output in 1 row


The code below allows me to see which e-learning module is accessed per day.

activity_per_day_which_modules <- ddply(activity, ~Date, distinct, `Which module(s)` = Module)

The output is as follows:

Date Module
22-10-2021 Food chemistry
22-10-2021 Food Physics

How do I tell R to combine the rows into one?

Date Module
22-10-2021 Food chemistry, Food physics
23-10-2021 Food chemistry

Solution

  • You can simply use paste for this:

    library(dplyr)
    
    df %>%
      group_by(Date) %>%
      summarize(Module = paste(Module, collapse = ", "))
    

    Note: If your real data has more columns you might want to resort to mutate rather than summarize, if you do just make sure to do %>% distinct() afterwards