R: Help writing a general function to prevent overwriting files when saving objects

Viewed 47

I'm trying to gain some control over when graphic objects are being saved and stumbled across this related post from 8+ years ago: https://stackoverflow.com/a/1541872/5322644 I'd like to come up with a more general approach and below is my current attempt. Of course, it doesn't work and so I'd appreciate some help on it.

 ## safely avoid overwriting files when saving objects using a user specified save.function 

safeSave <- function(save.function = save, ..., file=stop("'file' must be specified"), overwrite=FALSE ) {
  if ( file.exists(file) & !overwrite ) stop("'file' already exists")
  do.call(save.function, as.list( ..., file = file))
}
    
## Try using function.
## It appears to be trying to save the value of `tmp` rather than the variable `tmp`
tmp = 10
safeSave(save, tmp, file = "tmp.Rda") 
# Error in (function (..., list = character(), file = stop("'file' must be specified"),  : object ‘10’ not found
1 Answers

Here's what I learned: when using save(), use the name of your object as a string. I also changed as.list() to list(), but I'm not sure why this made a difference.

Your function with slight modifications:

safeSave <- function(save.function = save, ..., file=stop("'file' must be specified"), overwrite=FALSE ) {
  if ( file.exists(file) & !overwrite ) stop("'file' already exists")
  do.call(save.function, list(..., file = file))
}

I had some issues getting save() to work, so I tried saveRDS():

## Test with saveRDS()

tmp <- 10
file = "tmp.rds"
safeSave(saveRDS, tmp, file = file) 

# Check if file exists
file.exists(file)
#> [1] TRUE
# Correct contents
a <- readRDS(file)
a
#> [1] 10

# Attempt to overwrite
safeSave(save, "tmp", file = file)
#> Error in safeSave(save, "tmp", file = file): 'file' already exists

That worked fine.

Now save(). Note that I'm using "tmp" instead of tmp:

## Test with save()

file <- "tmp.rda"
tmp <- 10
safeSave(save, "tmp", file = file)

# Clean envir then load from file
rm(list=ls())
file <- "tmp.rda"
load(file)
tmp
#> [1] 10
Related