1

I have a dataframe in R that has repeated entries in column a:

a <- c("cat", "dog", "cat", "dog")
b <- c("siamese", "chow", "burmese", "husky")
dataframe <- data.frame(a,b)

   a       b
1 cat siamese
2 dog    chow
3 cat burmese
4 dog   husky

How do I collapse entries where a is repeated multiple times? For example, to end up with a dataframe like this:

   a       b
1 cat siamese; burmese
2 dog    chow; husky
icedcoffee
  • 935
  • 1
  • 6
  • 18

2 Answers2

2

You can use aggregate with paste setting collapse = "; "

aggregate(b ~ a, dataframe, paste, collapse = "; ")
#    a                b
#1 cat siamese; burmese
#2 dog      chow; husky
GKi
  • 37,245
  • 2
  • 26
  • 48
0

You can simply do :

dataframe %>% 
  group_by(a) %>%
  summarize(b = paste(b, collapse = ", "))
Jrm_FRL
  • 1,394
  • 5
  • 15
  • Error in FUN(X, ...) : argument "FUN" is missing, with no default. Note: I fixed the above error by changing spelling of summarize to summarise – icedcoffee Jun 08 '20 at 14:14