我试图找到 Box-Cox 变换的最佳“lambda”参数。
我使用的是MASS包中的实现,所以我只需要创建模型并提取 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
有趣的是,同样的代码也在函数之外工作。换句话说,出于某种原因,MASS包中的boxcox函数正在全局环境中寻找变量。
我真的不明白,到底发生了什么......你有什么想法吗?
PS 我没有提供软件/硬件规格,因为这个错误已成功复制到我朋友的许多笔记本电脑上。
PPS 我已经找到了解决预测包中初始问题的方法,但我仍然想知道,为什么这段代码不起作用。