title: Finding model (returned from for loops) with lowest AIC in R
body: <p>I am trying to find model with lowest AIC. Models are returned from two for loops that make possible combinations of columns. I am unable to make the function return model with lowest AIC. The code below demonstrates where I got stuck:</p>
  
  <pre><code>rm(list = ls())
  
  data &lt;- iris
  
  data &lt;- data[data$Species %in% c("setosa", "virginica"),]
  
  data$Species = ifelse(data$Species == 'virginica', 0, 1)
  
  mod_headers &lt;- names(data[1:ncol(data)-1])
  
  f &lt;- function(mod_headers){
      for(i in 1:length(mod_headers)){
      tab &lt;- combn(mod_headers,i)
      for(j in 1:ncol(tab)){
        tab_new &lt;- c(tab[,j])
        mod_tab_new &lt;- c(tab_new, "Species")
        model &lt;- glm(Species ~., data=data[c(mod_tab_new)], family = binomial(link = "logit"))
      }
      }
    best_model &lt;- model[which(AIC(model)[order(AIC(model))][1])]
    print(best_model)
  }
  
  f(mod_headers)
  </code></pre>
  
  <p>Any suggestions? Thanks!</p>