How to pass object in nested functions?
Asked Answered
G

1

7

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?

Godless answered 10/6, 2012 at 18:25 Comment(1)
Corrected base.name to basename in the code above. Thanks Matthew.Godless
B
7

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)
Boisterous answered 10/6, 2012 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.