使用dplyr连接列

时间:2015-02-26 21:10:34

标签: r dplyr

我有一个data_frame,我希望vector成为A中元素的串联。所以

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"

我的第一个倾向是在paste()内使用summarise,但这不起作用。

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

Hadley和Romain谈论GitHub问题中的类似问题,但我不能直接看到它是如何应用的。似乎应该有一个非常简单的解决方案,特别是因为paste()通常 会返回单个值。

2 个答案:

答案 0 :(得分:23)

您需要折叠粘贴中的值

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

答案 1 :(得分:1)

我的数据框如下:
  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)))