6

我试图找到 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 我已经找到了解决预测包中初始问题的方法,但我仍然想知道,为什么这段代码不起作用。

4

3 回答 3

5

有时,用户贡献的包并不总是能很好地跟踪在操作函数调用时执行调用的环境。对您来说最快的解决方法是将线路从

the_lm <- lm(x ~ 1, data = my_tmp)

the_lm <- lm(x ~ 1, data = my_tmp, y=True, qr=True)

因为如果调用未请求yand ,则函数会尝试通过调用使用这些参数重新运行,并且函数范围内的事情会变得混乱。qrlmboxcoxlmupdate

于 2016-09-27T15:27:39.513 回答
1

为什么不让 box-cox 来做配件呢?

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

  out <- boxcox(x ~ 1, data = my_tmp, plotit=FALSE) # Gives the error

  best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda
  return(best_lambda)
}

我认为您的范围问题是环境中不存在update.default哪些调用。如果我在这方面错了,请纠正我。eval(call, parent.frame())my_tmpboxcox

于 2016-09-27T15:34:17.747 回答
0

boxcox找不到您的数据。这可能是因为一些范围问题。
您可以将数据输入到boxcox功能中。

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, data = my_tmp) # feed data in here

  best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda
  return(best_lambda)
}

find_lambda(runif(100))
于 2016-09-27T15:30:23.277 回答