Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object in nested functions?

I'm trying to override save() in R so that it creates any missing directories before saving an object. I'm having trouble passing an object through one function to another 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 code above results in this error:

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

I realize that the problem is that the object 'obj1' doesn't exist inside my custom save() function, but I haven't yet figured out how to pass it from fun1 to base::save.

I have tried:

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

and:

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

with no success.

Any suggestions?

like image 441
D. Woods Avatar asked Jun 10 '12 18:06

D. Woods


1 Answers

You need to specify the parent's environment to '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")
}

In addition, use '=' to specify parameter names:

fun1(obj = 1)
like image 73
Matthew Lundberg Avatar answered Oct 25 '22 23:10

Matthew Lundberg