gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:56:36 24 4
gpt4 key购买 nike

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

上面的代码导致此错误:

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


我意识到问题在于我的自定义 save() 函数中不存在对象“obj1”,但我还没有弄清楚如何将它从 fun1 传递到 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' :

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 调用的参数。
fun1 <- function(obj) {
obj1 <- obj + 1
save(obj1,file="~/test/obj.RData")
}

此外,使用 '=' 指定参数名称:
fun1(obj = 1)

关于r - 如何在嵌套函数中传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com