How to pass object in nested functions?

社会主义新天地 提交于 2019-12-12 10:39:21

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/10971217/how-to-pass-object-in-nested-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!