0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.