Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings using group_by and summarise in r [duplicate]

Tags:

r

dplyr

I am trying to concatenate a column of strings together based on a grouping. I'm using code that seems identical to me to what others have used (e.g. use dplyr to concatenate a column) but it isn't working, and I can't figure out why.

a = tibble(
       x = c(1,2,1,2),
       z = c('1','2','3','4')
   )

a %>% group_by(x) %>% summarise(val=paste(z, collapse=" "))

Gives:

   val
1 1 2 3 4

It acts as if there was only one group. Yet when I do a different function, the grouping works properly:

a %>% group_by(x) %>% tally()
# A tibble: 2 × 2
      x     n
  <dbl> <int>
1     1     2
2     2     2

Any idea what the issue might be?

like image 793
Kewl Avatar asked May 13 '17 21:05

Kewl


1 Answers

It could be that plyr package was also loaded and masked the summarise function from dplyr as both of them have the same function name. One option is to use :: to specify the function from the dplyr package

a %>%
   group_by(x) %>%
   dplyr::summarise(val=paste(z, collapse=" "))
# A tibble: 2 x 2
#      x   val
#  <dbl> <chr>
#1     1   1 3
#2     2   2 4
like image 147
akrun Avatar answered Nov 14 '22 07:11

akrun