r - curve3d 找不到本地函数 "fn"

标签 r scoping

我正在尝试使用 curve3d emdbook 中的函数-package 创建一个在另一个函数内部定义的函数的等高线图,如下面的最小示例所示:

library(emdbook)
testcurve3d <- function(a) {
  fn <- function(x,y) {
    x*y*a
  }
  curve3d(fn(x,y))
}

出乎意料的是,这会产生错误
> testcurve3d(2)
 Error in fn(x, y) : could not find function "fn" 

而同样的想法适用于更基本的 curve base的功能-包裹:
testcurve <- function(a) {
  fn <- function(x) {
    x*a
  }
  curve(a*x)
}
testcurve(2)

问题是如何curve3d可以重写,使其按预期运行。

最佳答案

您可以暂时attach搜索路径的函数环境以使其工作:

testcurve3d <- function(a) {
  fn <- function(x,y) {
    x*y*a
  }
  e <- environment()
  attach(e)
  curve3d(fn(x,y))
  detach(e)
}

分析

问题来自 curve3d 中的这一行:
eval(expr, envir = env, enclos = parent.frame(2))

此时,我们似乎有 10 帧深,并且 fnparent.frame(8) 中定义.所以你可以编辑 curve3d 中的行使用它,但我不确定这有多健壮。也许 parent.frame(sys.nframe()-2)可能更健壮,但作为 ?sys.parent警告可能会发生一些奇怪的事情:

Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. So internal functions (which may or may not set contexts and so may or may not appear on the call stack) may not be counted, and S3 methods can also do surprising things.

Beware of the effect of lazy evaluation: these two functions look at the call stack at the time they are evaluated, not at the time they are called. Passing calls to them as function arguments is unlikely to be a good idea.

关于r - curve3d 找不到本地函数 "fn",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52293265/

相关文章:

r - 在 x 轴上的日期之间提供阴影

RNetLogo 不适用于 macOS Sierra 和 Windows

javascript - 在 for 循环中初始化的变量的作用域规则

python - 如何使用python引用可调用装饰器对象中的对象实例?

rust - 我无法理解 Rust "scope"定义(Rust 编程语言,第二版。Klabnik & Nichols)

R googleVis BubbleChart,设置大小而不设置颜色

r - 处理 RSelenium 错误消息

r - R中正态分布函数的逆/逆

Javascript 工厂模式变量作用域

Javascript - 在没有类型声明的情况下声明的匿名函数,它们应该是局部范围的吗?