【发布时间】:2023-03-16 02:20:01
【问题描述】:
我正在尝试为 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 函数正在全局环境中寻找变量。
我不太明白,到底是怎么回事……你有什么想法吗?
附:我没有提供软件/硬件规格,因为此错误已成功复制到我朋友的许多笔记本电脑上。
附言我在 forecast 包中找到了解决初始问题的方法,但我仍然想知道,为什么这段代码不起作用。
【问题讨论】:
标签: r scoping mass-package