Fabio Capezzuoli
Fabio Capezzuoli

Reputation: 619

Saving plots with different filenames using R

While fine-tuning parameters for plots I want to save all the test runs in different files so that they will not be lost. So far, I managed to do it using the code below:

# Save the plot as WMF file - using random numbers to avoid overwriting
  number <- sample(1:20,1)
  filename <- paste("dummy", number, sep="-")
  fullname <- paste(filename, ".wmf", sep="")
  # Next line actually creates the file
  dev.copy(win.metafile, fullname)
  dev.off() # Turn off the device

This code works, generating files with name "dummy-XX.wmf", where XX is a random number between 1 and 20, but it looks cumbersome and not elegant at all.

Is there any more elegant method to accomplish the same? Or even, to keep a count of how many times the code has been run and generate nice progressive numbers for the files?

Upvotes: 0

Views: 1622

Answers (2)

RockScience
RockScience

Reputation: 18580

If you really want to increment (to avoid overwriting what files already exist) you can create a small function like this one:

createNewFileName = function(path  = getwd(), pattern = "plot_of_something", extension=".png") {
  myExistingFiles = list.files(path = path, pattern = pattern)
  print(myExistingFiles)
  completePattern = paste0("^(",pattern,")([0-9]*)(",extension,")$")
  existingNumbers  = gsub(pattern = completePattern, replacement = "\\2", x = myExistingFiles)

  if (identical(existingNumbers, character(0)))
    existingNumbers = 0

  return(paste0(pattern,max(as.numeric(existingNumbers))+1,extension))
}

# will create the file myplot1.png
png(filename = createNewFileName(pattern="myplot"))
hist(rnorm(100))
dev.off()

# will create the file myplot2.png
png(filename = createNewFileName(pattern="myplot"))
hist(rnorm(100))
dev.off()

Upvotes: 2

MrFlick
MrFlick

Reputation: 206242

If you are printing many plots, you can do something like

png("plot-%02d.png")
plot(1)
plot(1)
plot(1)
dev.off()

This will create three files "plot-01.png", "plot-02.png", "plot-03.png"

The filename you specify can take an sprintf-like format where the index of the plot in passed in. Note that counting is reset when you open a new graphics device so all calls to plot() will need to be done before calling dev.off().

Note however with this method, it will not look to see which files already exist. It will always reset the counting at 1. Also, there is no way to change the first index to anything other than 1.

Upvotes: 1

Related Questions