将函数应用于dplyr的group_by的输出 [英] applying a function to the output of dplyr's group_by

查看:113
本文介绍了将函数应用于dplyr的group_by的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要分组一个大数据帧,并创建一个ggplot的每个分组。听起来像是dplyr的完美候选人,但是我遇到了调用 group_by 结果中的函数的问题。任何提示将不胜感激。

 #我想使用基本功能做什么:groupby列中的元素
#并为每个组创建/保存一个情节
(i在级别(iris $ Species)){
df = iris [iris $ Species == i,]
p< ; - ggplot(df,aes(x = Sepal.Length,y = Sepal.Width)+ geom_point())
ggsave(p,filename = paste(i,。pdf,sep =))
}

#我试图用dplyr
库(dplyr)
iris%>%
group_by(Species) %>%
do({
p < - ggplot(。,aes(x = Sepal.Length,y = Sepal.Width)+ geom_point())
ggsave(p,filename = paste(quote(Species),。pdf,sep =))
})


解决方案

嗯,你有一个括号问题和一个文件命名问题,所以也许这是你所指的。我假设

  iris%>%
group_by(Species)%>%
({
p< - ggplot(。,aes(x = Sepal.Length,y = Sepal.Width))+ geom_point()
ggsave(p,filename = paste0(unique(。$ Species) ,。pdf))
})

可以解决你的问题。 >

I would like to subset a large dataframe and create a ggplot of each grouping. Sounds like a perfect candidate for dplyr but I'm running into issues calling functions on the group_by results. Any hints would be greatly appreciated.

# what I want to do using base functions: "groupby" the elements in a column 
# and create/save a plot for each group
for (i in levels(iris$Species)){
  df = iris[iris$Species == i,]
  p <- ggplot(df, aes(x=Sepal.Length, y=Sepal.Width) + geom_point())
  ggsave(p, filename=paste(i,".pdf",sep=""))
}

# I'm trying to get something like this using dplyr
library(dplyr)
iris %>%
  group_by(Species) %>%
  do({
      p <- ggplot(., aes(x=Sepal.Length, y=Sepal.Width) + geom_point())
      ggsave(p, filename=paste(quote(Species),".pdf",sep=""))
     })

解决方案

Well, you have a parenthesis problem and a file naming problem so maybe it's one of those that you are referring to. I'm assuming

iris %>%
  group_by(Species) %>%
  do({
      p <- ggplot(., aes(x=Sepal.Length, y=Sepal.Width)) + geom_point()
      ggsave(p, filename=paste0(unique(.$Species),".pdf"))
     })

would fix your problem.

这篇关于将函数应用于dplyr的group_by的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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