0

I was just wondering if there was any way I could use vector elements to change/update text in R. At the moment I wish to save a large number of plots with ggplot2 using the ggsave function such that I have:

ggsave(filename= "xxxPlot.jpg", plot= xxx, scale = 1, width = 16, height= 8)

Now, since I have a large number of plots I wish to change the "xxxPlot.jpg" part so that the 'xxx' section is replaced with characters from a vector.

For example, let's say I have a vector of strings as follows:

vector <- c(AAA, BBB, CCC, DDD, EEE, FFF, GGG, HHH)

I wish to find a way to be able to change/update the line

ggsave(filename= "xxxPlot.jpg", plot= xxx, scale = 1, width = 16, height= 8)

to

ggsave(filename= "aaaPlot.jpg", plot= xxx, scale = 1, width = 16, height= 8)
ggsave(filename= "bbbPlot.jpg", plot= xxx, scale = 1, width = 16, height= 8)
ggsave(filename= "cccPlot.jpg", plot= xxx, scale = 1, width = 16, height= 8)

etc. automatically without having to manually write out each line and while using the vector I mentioned above (It's important to use the vector since the vector and plots are directly obtained from a data frame). Is there a way to do that in R? Thanks in advance.

ThePlowKing
  • 341
  • 1
  • 4
  • 15
  • 1
    First of all I'd make `vector` an actual character vector like `vector <- c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH")`, then you can just loop over a pasted string like `paste0(vector, "Plot.jpg")` – thelatemail May 03 '17 at 03:09
  • possible duplicate to the question [Saving multiple ggplots from ls into one and separate files in R](http://stackoverflow.com/questions/20500706/saving-multiple-ggplots-from-ls-into-one-and-separate-files-in-r) – Adam Quek May 03 '17 at 03:16
  • Assuming you don't want to save the same plot 8 times, you might need `Map` instead of `lapply`. – alistaire May 03 '17 at 03:24

1 Answers1

1

You can try this-

vector <- c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH")
    Plots<-paste(vector,"plot.jpg")
for (i in length(Plots)){
 ggsave(filename= Plots[i], plot= vector[i], scale = 1, width = 16, height= 8)

 }