【问题标题】:R Passing linear model to another function inside a functionR将线性模型传递给函数内的另一个函数
【发布时间】: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


    【解决方案1】:

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

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

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

    因为如果lm 调用未请求yqrboxcox 函数会尝试通过update 调用使用这些参数重新运行lm,然后事情就搞砸了在函数范围内。

    【讨论】:

      【解决方案2】:

      为什么不让 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 环境中不存在。如果我在这方面错了,请纠正我。

      【讨论】:

        【解决方案3】:

        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))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-15
          • 1970-01-01
          • 1970-01-01
          • 2019-07-25
          • 2019-08-19
          相关资源
          最近更新 更多