如何在嵌套函数中传递对象?

D. *_*ods 6 overriding r ellipsis save

我试图save()在R中覆盖,以便在保存对象之前创建任何缺少的目录.我使用省略号方法将对象通过一个函数传递给另一个函数时遇到问题.

我的例子:

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)
Run Code Online (Sandbox Code Playgroud)

上面的代码导致此错误:

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

我意识到问题是我的自定义save()函数中不存在对象'obj1',但我还没有弄清楚如何将它从fun1传递给base :: save.

我试过了:

base::save(parent.frame()$...,file=file.path(target.dir,basename(file)))
Run Code Online (Sandbox Code Playgroud)

和:

base::save(list=list(...),file=file.path(target.dir,basename(file)))
Run Code Online (Sandbox Code Playgroud)

没有成功.

有什么建议?

Mat*_*erg 7

您需要将父级环境指定为"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())
}
Run Code Online (Sandbox Code Playgroud)

请注意添加到base :: save调用的参数.

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

另外,使用'='指定参数名称:

fun1(obj = 1)
Run Code Online (Sandbox Code Playgroud)