如何在嵌套函数中传递对象? [英] How to pass object in nested functions?

查看:99
本文介绍了如何在嵌套函数中传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中覆盖save(),以便在保存对象之前创建所有丢失的目录.我在使用省略号方法将对象通过一个函数传递给另一个函数时遇到麻烦.

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.

我的例子:

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

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

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.

我尝试过:

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

和:

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

没有成功.

有什么建议吗?

推荐答案

您需要将父级的环境指定为'base :: save':

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())
}

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

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)

这篇关于如何在嵌套函数中传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆