Get all models from leaps regsubsets

☆樱花仙子☆ 提交于 2019-12-04 16:54:04

I don't know why you want a list of all models. summary and coef methods should serve you well. But I will first answer your question from a pure programming aspect, then come back to this point.


A simple way to do this is via reformulate:

reformulate(termlabels, response = NULL, intercept = TRUE)

Here is how:

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

There is no need for a *apply solution. lm is costly, so for loop has no overhead at all.


A faster way is to set up a model matrix containing all covariates, and select its columns dynamically (use assign attributes of the model matrix; especially true when you have factor variables). Model fitting is then via .lm.fit. However, you will have difficulty in producing model summary / prediction with raw output of .lm.fit unless you are a linear model guru, but I think summary(leaps) should return you various useful statistic already.

leaps:::coef.regsubsets function is an equivalence of this .lm.fit route. Simply do:

coef(leaps, 1:dim(X)[1], TRUE)

and you will get coefficients and variance-covariance matrix for all models.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!