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

前端 未结 2 1186
清酒与你
清酒与你 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.

提交回复
热议问题