gpt4 book ai didi

r - match.call 问题

转载 作者:行者123 更新时间:2023-12-04 10:27:27 25 4
gpt4 key购买 nike

我编写了一个使用 match.call 的函数,当我直接调用该函数时它可以工作,但是,当在另一个函数中调用该函数时它会中断。我相信这与 match.call 处理环境的方式有关,但我无法弄清楚。这是一个可重现的例子:

tester <- function() {

var <- "helloworld"

myFunc(var)

}


myFunc <- function(x) {

tmp <- match.call()
tmp[[1]] <- quote(toupper)
eval(tmp)

}

tester() # error

myFunc("helloworld") # works fine

我相信当在 tester 中调用 myFunc 时,它找不到 var 因为它存在于 的隔离环境中>测试器函数。

任何有关如何让 myFunctester 中工作的想法都将不胜感激。我已经尝试更改 evalmatch.call 的环境,但无济于事。

最佳答案

你的怀疑完全正确。

非常简单的解决方案是在其父上下文中评估函数:将 eval 替换为 eval.parent

myFunc <- function(x) {
tmp <- match.call()
tmp[[1]] <- quote(toupper)
eval.parent(tmp)
}

通常,函数 traceback 可以极大地帮助调试类似的问题:

> tester()
Error in as.character(x) :
cannot coerce type 'closure' to vector of type 'character'

好的,但是我们在谈论哪个“闭包”(= 函数)?

> traceback()
5: toupper(x = var)
4: eval(expr, envir, enclos)
3: eval(tmp) at #5
2: myFunc(var) at #5
1: tester()

第一行有线索:toupper(x = var)。在 tester 的上下文中,var 指的是函数(闭包)stats::var,因为它的包是附加的。

关于r - match.call 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180848/

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