I'd like to dynamically assign a plot to a variable name, and then call that variable latter on within a loop. While using "eval" outside of a loop seems to work just fine, placing it within a loop stops it from working as expected.
#Sample data frame
x<-c(1,2,3,4,5)
y<-c(5,4,3,2,1)
y2<-c(1,2,3,4,5)
DF<-data.frame(x,y,y2)
#Using ggplot for p and p2
p<-ggplot(DF, aes(x=x, y=y))+
geom_point()
p2<-ggplot(DF, aes(x=x, y=y2))+
geom_point()
#Assign p and p2 to string "Plot1" and "Plot2"
assign(paste0("Plot",1), p )
assign(paste0("Plot",2), p2 )
#Create a list to hold all plot names
plotlist<-c("Plot1", "Plot2")
#Print plots to a pdf
pdf(paste0("Plot", "_Test.pdf"), height =8, width=16)
for(i in seq(1,length(plotlist))){
plotname<-plotlist[i]
plotter<-eval(parse(text=plotname))
plotter
print(plotname)
}
dev.off()
Note that the above does not work. But if I am to run the same eval statements outside of the loop, AKA:
i=1
plotname<-plotlist[i]
plotter<-eval(parse(text=plotname))
plotter
The plot is created as expected. Is there a way to call "eval" within a loop? And what about being in a loop causes eval statement to work differently?
Note, by removing the for loop, it saves the (first) pdf as expected:
pdf(paste0("Plot", "_Test.pdf"), height =8, width=16)
#for(i in seq(1,length(plotlist))){
plotname<-plotlist[i]
plotter<-eval(parse(text=plotname))
plotter
print(plotname)
#}
dev.off()