且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编写函数以列出所有可能的模型组合

更新时间:2023-11-21 09:11:40

我不知道有任何软件包可以使它自动化.因此,让我们尝试一下蛮力方法.这个想法是手工生成所有可能的组合并对其进行迭代.

I am not aware of any packages that allow one to automate this. So, let's try a brute force approach. The idea is to generate all possible combinations by hand and iterate over them.

vars <- names(mtcars)[-1]

models <- list()

for (i in 1:5){
  vc <- combn(vars,i)
  for (j in 1:ncol(vc)){
    model <- as.formula(paste0("mpg ~", paste0(vc[,j], collapse = "+")))
    models <- c(models, model)
  }
}

您可以使用这些公式来运行线性模型.

You can use these formulas for run the linear model.

lapply(models, function(x) lm(x, data = mtcars))