【发布时间】:2023-08-18 09:51:01
【问题描述】:
下面显示的 R 代码是重现我无法理解的错误的最小工作示例。运行脚本应该会产生错误,Error in eval(expr, envir, enclos) : could not find function "fitModel"。在environments 上阅读了一两件事后,我想我明白为什么会在这种情况下发生这种情况,在“obscureFunction”的执行环境中没有定义“fitModel”。我通过对“myFormula”进行以下更改来解决此问题:
myFormula <- "y ~ eval(fitModel(x, a), envir = environment(fitModel))"
我不明白当在“obscureFunction”的调用环境中找不到函数时,如何在“fitModel”的环境中评估“fitModel”,换句话说我不明白为什么这段代码改变作品。我也不明白为什么如果“topFunction”的主体在没有调用它的情况下运行原始代码,即如果我们在R_GlobalEnv 中定义“fitModel”和“obscureFunction”并从控制台调用“obscureFunction”。
## Minimum Working Example to reproduce error
rm(list = ls())
library(minpack.lm)
topFunction <- function(){
fitModel <- function(x, a){
exp(-a * x)
}
## Create a function to use with lapply()
obscureFunction <- function(){
x <- seq(-1, 1, 0.01)
y <- exp(-0.5 * x)
Data <- data.frame(x, y)
init <- c(a = 1)
myFormula <- "y ~ fitModel(x, a)"
myFormula <- as.formula(myFormula)
nlsOutput <- nlsLM(formula = myFormula, start = init, data = Data)
return(nlsOutput)
}
## Function call
obscureFunction()
## Other calculations done with fitModel()
}
topFunction()
【问题讨论】:
-
@BrodieG 确实如此。评论已编辑。
标签: r