我正在尝试为 Box-Cox 变换找到最佳的“lambda”参数。
我正在使用 中的实现质量 包,所以我只需要创建模型并提取 lambda。
下面是函数的代码:
library(MASS)
find_lambda <- function(x) {
# Function to find the best lambda for the Box-Cox transform
my_tmp <- data.frame(x = x) # Create a temporary data frame, to use it with the lm
str(my_tmp) # Gives the expected output
the_lm <- lm(x ~ 1, data = my_tmp) # Creates the linear model, no error here
print(summary(the_lm)) # Prints the summary, as expected
out <- boxcox(the_lm, plotit=FALSE) # Gives the error
best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda
return(best_lambda)
}
find_lambda(runif(100))
它给出了以下错误:
Error in is.data.frame(data) : object 'my_tmp' not found
有趣的是,完全相同的代码在函数之外工作。换句话说,由于某种原因, boxcox 来自 的函数质量 包正在寻找全局环境中的变量。
我真的不明白,到底发生了什么......你有什么想法吗?
附言我不提供软件/硬件规范,因为这个错误已成功复制到我 friend 的许多笔记本电脑上。
P.P.S.我在 中找到了解决初始问题的方法预测包,但我仍然想知道,为什么这段代码不起作用。
最佳答案
有时,用户贡献的包并不总是能很好地跟踪在操作函数调用时执行调用的环境。对您来说最快的解决方法是将线路从
the_lm <- lm(x ~ 1, data = my_tmp)
到
the_lm <- lm(x ~ 1, data = my_tmp, y=True, qr=True)
因为如果
y
和 qr
未从 lm
请求打电话,boxcox
函数尝试重新运行 lm
通过 update
使用这些参数call 并且事情在函数范围内被搞砸了。
关于R将线性模型传递给函数内的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728374/