In the code below, how can I skip
ggsave(paste0(single_color,"_plot.png"))
when the code
plot_data <- diamonds %>% filter(color== single_color)
errors or plot_data
is empty ?
library(tidyverse)
data("diamonds")
colors_loop <- c(diamonds$color %>% as.character() %>% unique(),"Z")
for (single_color in colors_loop){
plot_data <- diamonds %>% filter(color== single_color)
plot_temp <- plot_data %>%
ggplot(aes(x,y))+geom_point()+labs(title=paste0(single_color,"_plot"))
ggsave(paste0(single_color,"_plot.png"))
}
To prevent an error if you supply a non-existent data frame to ggplot, you can use get0
. This checks for "existence", returning the object, otherwise NULL. To check for "emptiness" use nrow
.
colors_loop <- c(diamonds$color %>% as.character() %>% unique(),"Z")
my_plot <- function(data, cols) {
data <- get0(substitute(data))
if(is.null(data))
cat("No data to plot\n")
else {
for(single_color in cols) {
plot_data <- data %>% filter(color==single_color)
if(nrow(plot_data)>0) {
plot_temp <- plot_data %>%
ggplot(aes(x,y)) +
geom_point() +
labs(title=paste0(single_color,"_plot"))
cat(single_color, ": ")
ggsave(paste0(single_color, "_plot.png"))
}
}
}
}
my_plot(Diamonds, cols=colors_loop)
#No data to plot
my_plot(diamonds, cols=colors_loop)
#E : Saving 7 x 7 in image
#I : Saving 7 x 7 in image
#J : Saving 7 x 7 in image
#H : Saving 7 x 7 in image
#F : Saving 7 x 7 in image
#G : Saving 7 x 7 in image
#D : Saving 7 x 7 in image
my_plot(diamonds, cols=c("A", "E", "I", "O", "U"))
#E : Saving 7 x 7 in image
#I : Saving 7 x 7 in image