【问题标题】:R: test what objects a function takes from the enclosing environment [duplicate]R:测试函数从封闭环境中获取哪些对象[重复]
【发布时间】:2019-05-20 16:55:10
【问题描述】:

在定义 R 函数时,我有时会忽略它依赖于封闭环境中的对象。比如:

a <- 1
fn <- function(x) x + a

如果无意中发生这种情况,可能会导致难以调试的问题。

有没有一种简单的方法来测试fn 是否使用了封闭环境中的对象?

类似:

test(fn=fn, args=list(x=1))
## --> uses 'a' from enclosing environment

【问题讨论】:

  • 不是一个直接的答案,但可能会将exists("a",envir = .GlobalEnv) 添加到您的函数中,如果TRUE 则打印它来自例如全球环境的消息?
  • 感谢您对这些问题的指点。

标签: r function debugging testing environment


【解决方案1】:

一种可能性是使用codetools 包中的findGlobals 函数,该函数旨在:

查找闭包使用的全局函数和变量

这适用于您的示例:

#install.packages('codetools')
codetools::findGlobals(fn)
[1] "+" "a"

如果我们在函数内部定义a,它就会消失:

fn <- function(x) {
    a = 1
    x + a
}

codetools::findGlobals(fn)
[1] "{" "+" "="

但我没有在更复杂的事情上使用它,所以我不能说它对更复杂的功能有多准确。该文档附带以下警告:

结果是一个近似值。 R 语义只允许识别可能是本地的变量(以及假定不使用 assign 和 rm 的事件)。

【讨论】:

  • 我最终使用了codetools::findGlobals(fn, merge=FALSE)$variables
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2013-03-02
  • 1970-01-01
  • 2019-06-09
相关资源
最近更新 更多