1

I Have a data frame as follows:

df <- data.frame(Name = c("a","c","d","b","f","g","h"), group = c(2,1,2,3,1,3,1))

  Name group
   a     2 
   c     1
   d     2
   b     3
   f     1
   g     3
   h     1

I would like to use gather function from tidyverse package to reshape my data frame to the following format.

  group  Name total
    1   c,f,h   3
    2    a,d    2
    3    b,h    2

Do you know how can I do this?

Thanks,

say.ff
  • 373
  • 1
  • 7
  • 21
  • 1
    To understand gather, you can also have a look at [tidyexplain](https://github.com/gadenbuie/tidyexplain/tree/pkg#gather) – David Mar 27 '19 at 17:17

1 Answers1

3

We can group by 'group' and paste the elements of 'Name' with toString, while getting the total number of elements with n()

library(dplyr)
df %>% 
  group_by(group) %>%
  summarise(Name = toString(Name), total = n())
akrun
  • 874,273
  • 37
  • 540
  • 662