我不知道你为什么想要所有型号的列表。summary
and coef
方法应该对你很有用。但我会先从纯粹的编程方面回答你的问题,然后再回到这一点。
一个简单的方法是通过reformulate
:
reformulate(termlabels, response = NULL, intercept = TRUE)
具体方法如下:
## 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)
}
没有必要*apply
解决方案。lm
成本高昂,所以for
循环根本没有任何开销。
更快的方法是建立一个包含所有协变量的模型矩阵,并动态选择其列(使用assign
模型矩阵的属性;当你有因子变量时尤其如此)。然后通过模型拟合.lm.fit
。但是,您将很难使用以下原始输出生成模型摘要/预测.lm.fit
除非你是线性模型大师,但我认为summary(leaps)
应该已经返回您各种有用的统计数据。
leaps:::coef.regsubsets
函数是这个的等价物.lm.fit
路线。只需执行以下操作:
coef(leaps, 1:dim(X)[1], TRUE)
您将获得所有模型的系数和方差-协方差矩阵。