admin管理员组文章数量:1333160
I am trying to save a specific plot using ggplot and ggsave in a loop when certain conditions are met. The desired behavior of the loop is to save filtered plots in directory A, but under a certain condition (i.e. cyl=8) save the plot in a different directory. Ideally, I would like to save all plots in directory A and save a copy in directory B for certain conditions. Currently I am stuck. I have tried using if_else for a conditional save but saves in both locations. Is there a base R function that can do this better? Also open to suggestions on if there is a better vectorized way to generate these plots other than a loop which takes a lot of time. Any help or suggestions would be much appreciated.
library(tidyverse)
a <- mtcars
a$car_name <- row.names(a)
#loop through data
for (i in 1:NROW(a)) {
a1 <- filter(a, car_name == car_name[i]) #create car specific df
ggplot()+
geom_col(a1, mapping = aes(car_name, mpg))
directory_a <- paste("C:/cars_with_8_cylinders/", a1$car_name[1], ".png")
directory_b <- paste("C:/individual_car_graph/", a1$car_name[1], ".png")
if_else(a1$cyl == 8, ggsave(file = directory_a), ggsave(file =directory_b))
}
本文标签: if statementifelse for conditional ggsaveStack Overflow
版权声明:本文标题:if statement - if_else for conditional ggsave - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742350273a2458349.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论