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

查看:14
本文介绍了使用 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"

我的第一个倾向是在 summarise 中使用 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天全站免登陆