dplyr 中的字符串操作/聚合 [英] String Manipulation/Agregation in dplyr

查看:20
本文介绍了dplyr 中的字符串操作/聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行 group_by 并使用 dplyr 对数据框进行字符串操作

I want to perform group_by and do a string operation for a data frame using dplyr

df<-data.frame(varx=c("x1","x1","x2","x2","x2"),vary=c("y1","y2","y3","y4","y5"))

我希望输出 (newdf) 如下所示:

I want the output (newdf) to look like this:

newdf <- data.frame(varx=c("x1","x2"),catY=c("y1,y2","y3,y4,y5"))

我在 dplyr 中尝试了以下操作

I tried the following in dplyr

df %>% group_by(varx)%>%summarise(catY=paste(vary))
Error: expecting a single value

还尝试了以下方法:

df %>% group_by(varx)%>%mutate(catY=paste(vary))

Source: local data frame [5 x 3]
Groups: varx

我可以使用基本的数据框操作来完成.需要帮助了解 dplyr 中的出路.

I can do it using basic data frame operation. Need help in understanding a way out in dplyr.

推荐答案

David 评论的略短版本是:

The slightly shorter version of David's comment would be:

library(dplyr)
df %>% group_by(varx) %>% summarise(catY = toString(vary))

#Source: local data frame [2 x 2]
#
#  varx       catY
#1   x1     y1, y2
#2   x2 y3, y4, y5

这篇关于dplyr 中的字符串操作/聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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