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))
}