【问题标题】:How do I use lm() from inside a function?如何在函数内部使用 lm()?
【发布时间】:2016-03-31 13:12:20
【问题描述】:

似乎从函数内部或通过lapply 调用lm() 会破坏与拟合相关联的$call。最小的工作示例:

> library(MASS)
> dat <- data.frame(x = 1:100, y=1:100)
> dat <- within(dat, z <- x + log(y) + rnorm(100))
> fits <- lapply(list(z ~ x + y, z ~ x + log(y)), lm, dat)
> stepAIC(fits[[1]])               # <-- error when I try to use the fit in other functions
Error in eval(expr, envir, enclos) : could not find function "FUN"

> fits[[1]]$call
FUN(formula = X[[i]], data = ..1)  # Aha -- this must be why -- $call is screwed up

如何解决此问题并防止出现上述错误?

【问题讨论】:

标签: r regression linear-regression lm


【解决方案1】:

有时最好向lapply 提供匿名函数:

fits <- lapply(list(z ~ x + y, z ~ x + log(y)), 
                   function(f) lm(f, data = dat))
stepAIC(fits[[1]])
#works

请注意,这(通常是我首选的明确范围界定方式)不起作用,因为stepAIC 找不到DF

fits <- lapply(list(z ~ x + y, z ~ x + log(y)), 
                   function(f, DF) lm(f, data = DF), DF = dat)

注意逐步回归is a bad method anyway

【讨论】:

    【解决方案2】:

    另一种方法是直接在lapply 中应用stepAIC

     AICs <- lapply(list(z ~ x + y, z ~ x + log(y)), 
                    function(x) stepAIC(lm(x,dat)))
    

    这会为您提供所有模型的stepAIC 输出列表。

    【讨论】:

      【解决方案3】:

      尝试使用 this 作为 lapply 中的函数。这会在 fits 中生成漂亮的公式,显示实际公式,stepAIC 有效:

      fun <- function(fo) do.call("lm", list(fo, quote(dat)))
      fits <- lapply(list(z ~ x + y, z ~ x + log(y)), fun)
      

      给予:

      > fits[[1]]
      
      Call:
      lm(formula = z ~ x + y, data = dat)
      
      Coefficients:
      (Intercept)            x            y  
            2.154        1.031           NA  
      
      
      > stepAIC(fits[[1]])
      Start:  AIC=-3.34
      z ~ x + y
      
      
      Step:  AIC=-3.34
      z ~ x
      
             Df Sum of Sq   RSS    AIC
      <none>                 93  -3.34
      - x     1     88600 88693 680.78
      
      Call:
      lm(formula = z ~ x, data = dat)
      
      Coefficients:
      (Intercept)            x  
            2.154        1.031  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 2021-02-10
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多