I know this question has been asked before, but I found none of the answers where clear enough for me to understand how to solve my problem. I am looping over several variables to create graphs. The thing is, I want to save each of the graphs in the environment and combine them using ggsave. The problem I have is that all the graphs stored in the R environment are the same and correspond to the last graph in the loop.
Here is the data I am using. My code is the following:
# DEFINING VARIABLES
varnames <- c("firstborn", "gradet0", "p_educ")
#LOOPING OVER THEM:
for (var in varnames) {
var_m <- data[[paste(var,"m", sep="_")]]
var_se <- data[[paste(var,"se", sep="_")]]
varf <- data[[var]]
#CREATING GRAPHS:
plot <- ggplot(data, aes(x=var1_, y=var_m, fill=factor(varf))) +
geom_bar(stat = "identity", color="black",
position=position_dodge()) +
geom_errorbar(aes(ymin=var_m-1.96*var_se, ymax=var_m+1.96*var_se), width=.2,
position=position_dodge(.9)) +
theme_classic() +
labs(x =var, y = "Predicted values") +
scale_x_discrete(limits = c("noteen_female", "noteen_male", "teen_female",
"teen_male"),
labels = c("Female", "Male",
"Teen Mother", "Teen Father")) +
scale_fill_brewer(palette="Oranges") +
theme(legend.title = element_blank())
# TRYING TO SAVE TO THE R ENVIRONMENT
plot_var_name <- str_c(c("plot", var), collapse = "_")
assign(plot_var_name, plot)
# SAVING TO THE PC:
ggsave(paste("graph_",var,".png",sep=""), width = 200,
height = 100,
units = c("mm"),)
}
# COMBINING GRAPHS:
ggarrange(plot_firstborn, plot_gradet0, plot_p_educ,
ncol = 2, nrow = 2)
Whilst ggsave works well, the stored graphics in R environment are all the same. I am still an R newbie, so kind help/explanation would be greatly appreciated.