我正在尝试在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)更多推荐
如何在嵌套函数中传递对象?
发布评论