使用 dplyr 连接列

use dplyr to concatenate a column

我有一个 data_frame,我希望 vectorA 中元素的串联。所以

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

应该变成

newdf
Source: local data frame [4 x 2]

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

我的第一个想法是在 summarise 中使用 paste() 但这行不通。

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

Hadley 和 Romain 在 GitHub 问题中讨论了类似的问题,但我不太明白这如何直接适用。似乎应该有一个非常简单的解决方案,特别是因为 paste() 通常 return 单个值。

您需要折叠粘贴中的值

df %>% group_by(id) %>% summarise(vector=paste(A, collapse=" "))

我的数据框是:
col1 col2

1           one 
1           one more
2           two
2           two
3           three

我需要总结如下:

col1 col3

1           one, one more
2           two
3           three

以下代码起到了作用:

    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)))