Reputation: 2859
I am trying to print out and save to ggplot2 object (with a proper name with may change for each element of p.vec) using for loops, any help will be appreciated, many thanks in advance.
par(mfrow = c(2, 2))
p.vec <- c("disp","mpg")
for(i in p.vec){
p <- ggplot(data = mtcars, aes(x = mpg, y= i)) +geom_jitter()
print(p)
#ggsave("plot.pdf")
}
Upvotes: 0
Views: 137
Reputation: 388807
Try using lapply
:
library(ggplot2)
p.vec <- c("disp","mpg")
lapply(p.vec, function(x) {
p <- ggplot(data = mtcars, aes(x = mpg, y= .data[[x]])) +geom_jitter()
ggsave(sprintf('plot_%s.jpg', x))
})
Instead of .data[[x]]
you can also use any of the option from this answer.
Upvotes: 1