我正在尝试使用 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 帧深,并且
fn
在 parent.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/