如何在函数内部使用lm()?

mch*_*hen 0 regression r linear-regression lm

似乎lm()从一个函数内部调用或通过lapply拧紧$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
Run Code Online (Sandbox Code Playgroud)

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

Rol*_*and 6

有时最好提供匿名功能lapply:

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

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

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

请注意,逐步回归无论如何都是一种糟糕的方法.