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

编程入门 行业动态 更新时间:2024-10-16 20:20:15
本文介绍了如何在嵌套函数中传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在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)

更多推荐

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

本文发布于:2023-07-14 19:58:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   函数   对象   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!