Creating a loop through a list of variables for an LM model in R

前端 未结 2 1185
清酒与你
清酒与你 2020-12-12 01:12

I am trying to create multiple linear regression models from a list of variable combinations (I also have them separately as a data-frame if that is more useful!)

Th

相关标签:
2条回答
  • 2020-12-12 01:43

    You don't even have to use loops. Apply should work nicely.

    training_data <- as.data.frame(matrix(sample(1:64), nrow = 8))
    colnames(training_data) <- c("independent_variable", paste0("x", 1:7))
    
    Vars <- as.list(c("x1+x2+x3",
                    "x1+x2+x4",
                    "x1+x2+x5",
                    "x1+x2+x6",
                    "x1+x2+x7"))
    
    allModelsList <- lapply(paste("independent_variable ~", Vars), as.formula)
    allModelsResults <- lapply(allModelsList, function(x) lm(x, data = training_data))  
    

    If you need models summaries you can add :

    allModelsSummaries = lapply(allModelsResults, summary) 
    

    For example you can access the coefficient R² of the model lm(independent_variable ~ x1+x2+x3) by doing this:

    allModelsSummaries[[1]]$r.squared
    

    I hope it helps.

    0 讨论(0)
  • 2020-12-12 02:06

    We can create the formula with paste

    out <- vector('list', length(var_list))
    
    for (i in seq_along(var_list)){
      out[[i]] <- lm(paste('independent_variable',  '~', var_list[i]),
                   data = training_data)
     }
    

    Or otherwise, it can be done with reformulate

    lm(reformulate(var_list[i], 'independent_variable'), data = training_data)
    
    0 讨论(0)
提交回复
热议问题