Question

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..

Was it helpful?

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

OTHER TIPS

Another way is to substitute your line:

model1 = lmer(varname ~ + (1 | par1) + (1 | par2), data=df)

with

model1 = lmer(paste0(varname," ~ + (1 | par1) + (1 | par2)"), data=df)

This will pass the formula as a string, which lmer(...) will coerce to a formula.

Here is another approach.. seems a bit more complicated.. but thought I would add it for completeness: R: analyzing multiple responses (i.e. dependent variables) in a mixed effects model (lme4)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top