how to call function through for loop to generate multiple plots

I want to do the same thing on different dataset with the same data structure.
The function generates histogram in RStudio plots window based on subset of data.
it works if call function one by one, like
iris_hist(iris,"setosa")
iris_hist(iris,"versicolor")
iris_hist(iris,"virginica")
but failed if call it through for loop. How to make for loop work? Thanks in advance!

iris_hist <- function(ds,type) {
ds <- ds %>% filter(Species == type ) 
hist_titl<-paste0("histogram for ", type)
ggplot(ds, aes(x=Petal.Length, y=..count..)) + 
  geom_histogram(bins=50, fill="steelblue", color="white") + 
  ggtitle(hist_titl)
}

types<-iris %>% select(Species) %>% unique()
for (i in 1:nrow(types)){
  t<-types[i,1]
  iris_hist(iris,t)
} 

Try using purrr.

Awesome! After change data shape, it works as expected. Thank you!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.