Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

r - applying a function to the output of dplyr's group_by

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=""))
     })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...