字符串操作/在dplyr中的聚集 [英] String Manipulation/Agregation in dplyr
本文介绍了字符串操作/在dplyr中的聚集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用dplyr执行group_by并对数据框执行字符串操作
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
我可以使用基本的数据框架操作。
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屋!
查看全文