最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if statement - if_else for conditional ggsave - Stack Overflow

programmeradmin0浏览0评论

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))
}
发布评论

评论列表(0)

  1. 暂无评论