reo*_*eox 3 regression r linear-regression lm
我使用 regsubsets 来搜索模型。是否可以lm从参数选择列表中自动创建所有内容?
library(leaps)
leaps<-regsubsets(y ~ x1 + x2 + x3, data, nbest=1, method="exhaustive")
summary(leaps)$which
(Intercept) x1 x2 x3
1 TRUE FALSE FALSE TRUE
2 TRUE FALSE TRUE TRUE
3 TRUE TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
现在我会手动做model_1 <- lm(y ~ x3)等等。如何自动将它们放在列表中?
我不知道你为什么想要所有模型的列表。summary和coef方法应该很好地为您服务。但我将首先从纯编程方面回答您的问题,然后再回到这一点。
一个简单的方法是通过reformulate:
reformulate(termlabels, response = NULL, intercept = TRUE)
Run Code Online (Sandbox Code Playgroud)
方法如下:
## you are masking `leaps` and `data` function!!
leaps <- regsubsets(y ~ x1 + x2 + x3, data, nbest = 1, method = "exhaustive")
X <- summary(leaps)$which
xvars <- dimnames(X)[[2]][-1] ## column names (all covariates except intercept)
responsevar <- "y" ## name of response
lst <- vector("list", dim(X)[1]) ## set up an empty model list
## loop through all rows / model specifications
for (i in 1:dim(X)[1]) {
id <- X[i, ]
form <- reformulate(xvars[which(id[-1])], responsevar, id[1])
lst[[i]] <- lm(form, data)
}
Run Code Online (Sandbox Code Playgroud)
不需要*apply解决方案。lm成本很高,因此for循环根本没有开销。
一种更快的方法是建立一个包含所有协变量的模型矩阵,并动态选择其列(使用assign模型矩阵的属性;当您有因子变量时尤其如此)。模型拟合然后通过.lm.fit。但是,.lm.fit除非您是线性模型专家,否则您将难以使用原始输出生成模型摘要/预测,但我认为summary(leaps)应该已经为您返回各种有用的统计数据。
leaps:::coef.regsubsets功能是这.lm.fit条路线的等价物。简单地做:
coef(leaps, 1:dim(X)[1], TRUE)
Run Code Online (Sandbox Code Playgroud)
您将获得所有模型的系数和方差-协方差矩阵。
| 归档时间: |
|
| 查看次数: |
2244 次 |
| 最近记录: |