使用dplyr将组串连接 [英] Concatenate strings by group with dplyr

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

问题描述

我有一个数据框看起来像这样

i have a dataframe that looks like this

> data <- data.frame(foo=c(1, 1, 2, 3, 3, 3), bar=c('a', 'b', 'a', 'b', 'c', 'd'))
> data
  foo bar
1   1   a
2   1   b
3   2   a
4   3   b
5   3   c
6   3   d

我想创建一个新的列bar_by_foo,它是由foo的值连接起来的。所以新数据应该如下所示:

I would like to create a new column bars_by_foo which is the concatenation of the values of bar by foo. So the new data should look like this:

  foo bar bars_by_foo
1   1   a          ab
2   1   b          ab
3   2   a           a
4   3   b         bcd
5   3   c         bcd
6   3   d         bcd

我希望以下内容可以正常工作:

I was hoping that the following would work:

p <- function(v) {
  Reduce(f=paste, x = v)
}
data %>% 
  group_by(foo) %>% 
  mutate(bars_by_foo=p(bar))

但该代码给我一个错误

错误:不兼容的类型,期待一个字符向量

我在做什么

推荐答案

你可以简单地做

data %>% 
     group_by(foo) %>% 
     mutate(bars_by_foo = paste0(bar, collapse = "")) 

没有任何帮助函数

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

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