[英]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. 我试图覆盖R中的
save()
,以便在保存对象之前创建任何缺少的目录。 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. 我意识到问题是我的自定义save()函数中不存在对象'obj1',但我还没有弄清楚如何将它从fun1传递给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? 有什么建议?
You need to specify the parent's environment to 'base::save' : 您需要将父级环境指定为“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. 请注意添加到base :: save调用的参数。
fun1 <- function(obj) {
obj1 <- obj + 1
save(obj1,file="~/test/obj.RData")
}
In addition, use '=' to specify parameter names: 另外,使用'='指定参数名称:
fun1(obj = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.