How to pass an object to nested functions?

I am trying to override save()in R so that it creates all the missing directories before saving the object. I am having trouble passing an object through a single function using the ellipsis method.

My example:

save <- function(...,file){ #Overridden save()
  target.dir <- dirname(file) #Extract the target directory
  if(!file.exists(target.dir)) {
      #Create the target directory if it doesn't exist.
      dir.create(target.dir,showWarnings=T,recursive=T)
  }
  base::save(...,file=file.path(target.dir,basename(file)))
}

fun1 <- function(obj) {
  obj1 <- obj + 1
  save(obj1,file="~/test/obj.RData")
}

fun1(obj = 1)

The above code results in an error:

Error in base::save(..., file = file.path(target.dir, basename(file))) : 
object β€˜obj1’ not found

I understand that the problem is that the obj1 object does not exist inside my user-defined save () function, but I still have not figured out how to pass it from fun1 to base :: save.

I tried:

base::save(parent.frame()$...,file=file.path(target.dir,basename(file)))

and

base::save(list=list(...),file=file.path(target.dir,basename(file)))

without success.

Any suggestions?

+5
source share
1 answer

You need to specify the parent environment "base :: save":

save <- function(...,file){ #Overridden save()
  target.dir <- dirname(file) #Extract the target directory
  if(!file.exists(target.dir)) {
    #Create the target directory if it doesn't exist.
    dir.create(target.dir,showWarnings=T,recursive=T)
  }
  base::save(...,file=file.path(target.dir,basename(file)),envir=parent.frame())
}

Note the parameter added to the base :: save call.

fun1 <- function(obj) {
  obj1 <- obj + 1
  save(obj1,file="~/test/obj.RData")
}

Also use '=' to specify parameter names:

fun1(obj = 1)
+7

All Articles