编写函数以列出所有可能的模型组合 [英] Write a function to list all possible combinations of models

查看:55
本文介绍了编写函数以列出所有可能的模型组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来为数据集中的变量运行所有可能的回归模型.我能够运行每个变量,这是我到目前为止所拥有的.

I'm attempting to write a function to run all possible regression models for variables in a dataset. I was able to get it to run each variable, this is what I have so far.

library(tidyverse)
library(broom)
data("mtcars")

model1 <- function (DATA) {
DATA %>%
  map(~lm(mpg ~ .x, data = DATA), tidy)%>%   map(summary) %>% 
  map_dbl("adj.r.squared") %>%
  tidy %>% 
  rename(adj.r.squared = x)
}

model1(mtcars) 

我是R和编写函数的新手,所以我确定它存在一些问题.我希望为所有可能的模型提供所有调整后的r平方值的详细信息.如何编写对两个,三个或更多变量执行相同操作的函数?

I am new to R and writing functions so I am sure there are some issues with it. I want a tibble of all the adjusted r squared values for all possible models. How do I write a function that will do the same thing for two, three, or more variables?

推荐答案

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

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

这篇关于编写函数以列出所有可能的模型组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆