rloopsmlm

Looping through columns to analyse different dependent variable


Here my data frame (reproducible example)

   set.seed(42)  
n <- 6
dat <- data.frame(id=rep(1:n, 2), 
                  group= as.factor(rep(LETTERS[1:2], n/2)),
                  VD1 = rnorm(n),
                  VD2 = runif(n*2, min=0, max=100), 
                  VD3 = runif(n*2, min=0, max=100),
                  VD4 = runif(n*2, min=0, max=100),
                  VD5 = runif(n*2, min=0, max=100)) 

I am fitting the following mlm for one dependent variable "VD1"

> mlm_VD1  <- lmer(formula = VD1 ~ group + (1|id)
>                   , data = dat) 

    summary(mlm_VD1)

I would like to automatize the analyses of all the other dependent variables VD2, VD3, VD4, VD5 by creating a loop through all the columns of my dataframe (dat[, 4:ncol(dat)])

I would like then to save all the summaries of the different mlm (mlm_VD1, mlm_VD2, mlm_VD3, mlm_VD4, mlm_VD5) in a pdf file to read outside the R environment

Thanks!


Solution

  • Adding to the solution provided by akrun..

    library(broom.mixed)
    library(lme4)
    library(purrr)
    

    Indexing the columns as 3:7

    var_names <- names(dat)[3:7]
    
    output <- map_dfr(var_names,
                      function(x){
                        formula_mlm = as.formula(paste0(x,"~ group + (1|id)"));
                        model_fit = lmer(formula_mlm,data=dat) %>% 
                          tidy(.) %>% 
                          dplyr::mutate(variable = x);
                        return(model_fit)
                        
                      })
    output %>% 
    +   head(.)
    
    
       # A tibble: 6 x 7
      effect   group    term            estimate std.error statistic variable
      <chr>    <chr>    <chr>              <dbl>     <dbl>     <dbl> <chr>   
    1 fixed    NA       (Intercept)      7.80e-1     0.223      3.50 VD1     
    2 fixed    NA       groupB          -7.59e-1     0.315     -2.41 VD1     
    3 ran_pars id       sd__(Intercept)  3.74e-1    NA         NA    VD1     
    4 ran_pars Residual sd__Observation  2.10e-8    NA         NA    VD1     
    5 fixed    NA       (Intercept)      7.91e+1    13.2        5.98 VD2     
    6 fixed    NA       groupB          -2.97e+1    18.7       -1.59 VD2