I am trying to find a way to stop accidental overwriting of files when using the save() and save.image() function in R.
+3
A:
Use file.exists()
to test if the file is there, and if it is, append a string to the name.
Edit:
Thanks Marek, I'll expand on your idea a bit... he could add this to deal with both save()
and save.image()
SafeSave <- function( ..., file=stop("'file' must be specified"), overwrite=FALSE, save.fun=save) {
if ( file.exists(file) & !overwrite ) stop("'file' already exists")
save.fun(..., file=file)
}
I would not overwrite save... if source()
was used in a REPL session, users may not be aware of the function overwrite.
Vince
2009-10-09 04:57:15
Does anyone know how to create a dialog box to notify the user that the file to be written already exists? The user may just close the R session without knowing and nothing is saved.
ggg
2009-10-10 09:13:36
+4
A:
As Vince wrote you could use file.exists()
to check existence.
I suggest to replace original save
function:
save <- function( ..., file=stop("'file' must be specified"), overwrite=FALSE ) {
if ( file.exists(file) & !overwrite ) stop("'file' already exists")
base::save(..., file=file)
}
You could write similar to replace save.image()
.
Marek
2009-10-09 09:03:14