16

I have a data_frame where I would like vector to be the concatenation of elements in A. So

df <- data_frame(id = c(1, 1, 2, 2), A = c("a", "b", "b", "c"))
df
Source: local data frame [4 x 2]

  id A
1  1 a
2  1 b
3  2 b
4  2 c

Should become

newdf
Source: local data frame [4 x 2]

  id vector
1  1 "a b"
2  2 "b c"

My first inclination is to use paste() inside summarise but this doesn't work.

df %>% group_by(id) %>% summarise(paste(A))
Error: expecting a single value

Hadley and Romain talk about a similar issue in the GitHub issues, but I can't quite see how that applies directly. It seems like there should be a very simple solution, especially because paste() usually does return a single value.

gregmacfarlane
  • 2,121
  • 3
  • 24
  • 53

2 Answers2

40

You need to collapse the values in paste

df %>% group_by(id) %>% summarise(vector=paste(A, collapse=" "))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    Wow, okay. Have never used `collapse` because it seems awfully similar to `sep`. This is the kind of thing I love about R! – gregmacfarlane Feb 26 '15 at 21:17
  • @MrFlick, could you please advise how I can use your solution for only pasting unique values of `A` while there are duplicates values of `A` corresponding to an `ID`? Thanks! – Alex May 27 '21 at 07:08
  • 1
    @Alex You can use `vector=paste(unique(A), collapse=" ")` – MrFlick May 27 '21 at 07:14
  • @MrFlick, Thank you! I will try on the data and will keep you posted! – Alex May 27 '21 at 07:15
2

My data frame was as:
col1 col2

1           one 
1           one more
2           two
2           two
3           three

I needed to summarise it as follows:

col1 col3

1           one, one more
2           two
3           three

This following code did the trick:

    df <- data.frame(col1 = c(1,1,2,2,3), col2 = c("one", "one more", "two", "two", "five"))

    df %>%
            group_by(col1) %>%
            summarise( col3 = toString(unique(col2)))
Nasir
  • 167
  • 6
  • But this will essentially make it a string. A comma separated string. How to get data something like 1. Design_ID 2. Vector of designs not comma separate values. – sriharsha KB Sep 02 '16 at 08:39