Q:

How to protect an existing file from overwriting with pdf function in R

I'm saving lots of images with the function pdf() in R. My function works really fine, but I have the problem, that some of my images will get overwritten if I'm not careful enough. 
Is there a possibility to protect created pdf files from being overwritten, when I try to save in the same file with the same name?
For example:
 x = plot(1,2)
 pdf("C:\\users\\documents\\image1.pdf")
 pdf("C:\\users\\documents\\image1.pdf")

And the second command will force an error?

A:

You might check if your file already exists and throw a warning if your script tries to overwrite it. You might try something like this:
file <- "C:\\users\\documents\\image1.pdf"

    if(!file.exists(file)){
      pdf(file)

    }else{
        warning("File does already exist!")
    }

Is this what you want to achieve?
Going further, you might use the else section to create a new filename using something like gsub() and / or paste() in order to save the new file without overwriting the old one.

