Search code examples
rfunctionlmer

How to run a model for multiple variables(columns) in df with lmer


I have several variables(columns) in a df I want to run lmer (from lme4 package).
Say I have a dataframe called df:

par1   par2 resp1 resp2
plant1 rep1 3     8
plant2 rep2 5     2
...

I'm trying to write a function to do this, but having trouble passing arguments and using them in the function.

model1 = function(df, varname){
  library(lme4)
  model1 = lmer(varname ~ + (1 | par1) + (1 | par2), data=df)
  return(model1)
}

resp1model = model1(df, "resp1")
resp2model = model1(df, "resp2")

Can someone advise on the best way to do this? Maybe a function isn't the answer? A loop? I should say the reason is that once I get the function working, I want the function to return other things from the model.. such as the AIC, BLUPs, etc..


Solution

  • I did this way, may be even better

    varlist=names(df)[i:j] #define what vars you want
    
    blups.models <- lapply(varlist, function(x) {
      lmer(substitute(i ~ (1|par1)+(1|par2)+(1|par3), list(i = as.name(x))), data = df, na.action=na.exclude)
    })
    

    here you have the list of models for all vars you want