使用dplyr连接列 [英] use dplyr to concatenate a column

查看:79
本文介绍了使用dplyr连接列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data_frame 我希望 vector 成为 A 。所以

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

应该成为

newdf
Source: local data frame [4 x 2]

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

我的第一个倾向是使用 paste()里面总结,但这不行。

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和Romain谈到了一个类似的问题,在 GitHub 问题,但我看不出直接适用的方式。似乎应该有一个非常简单的解决方案,特别是因为 paste()通常 返回一个值。

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.

推荐答案

您需要折叠粘贴中的值

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

这篇关于使用dplyr连接列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆