0
votes

How can I code a FOR loop (or some other function) to refit linear models?

I am performing an exhaustive search of multiple linear regression models with the R package leaps. The package does return vectors of certain fit statistics (i.e. BIC and r-squared). However, there are a few other fit criteria (i.e. CCC) I would like to generate for a subset of the models (~100). Instead of fitting the subset of models manually, I want to leverage a data.frame provided by leaps for automated refitting of predictive multiple linear models.

I have two data.frames to use: 1) the data (response + all explanatory variables) and 2) a data.frame describing what variables where in each model. The second data.frame has boolean (TRUE/FALSE) indicators of whether each explanatory variable (columns) was incorporated in the linear model (rows). Below is a representation of that data.frame.

     (Intercept)    var1  var2 var3   
X5          TRUE    TRUE FALSE FALSE 
X6          TRUE    TRUE FALSE FALSE 
X7.2        TRUE    TRUE FALSE FALSE 
X7.4        TRUE    TRUE FALSE FALSE 
X8.2        TRUE    TRUE FALSE  TRUE
1

1 Answers

0
votes

Consider lapply across the boolean data frame building formulas dynamically from TRUE columns. Be sure to adjust response to actual variable in below string.

model_list <- lapply(1:nrow(bool_df), function(i) {    
    tmp <- as.vector(bool_df[i,-1])
    eq <- paste("response ~ ", 
                paste(names(tmp)[tmp == TRUE], collapse=" + "))

    lm(as.formula(eq), data_df)
})

Rextester demo (building formulas only)