3

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

Paul
  • 475
  • 8
  • 17

3 Answers3

4

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

Ananta
  • 3,671
  • 3
  • 22
  • 26
2

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.

jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • 4
    or `form <- reformulate("~(1|par1)+(1|par2)",response=varname); lmer(form, data=df)` – Ben Bolker Mar 03 '14 at 00:06
  • Thanks! These suggestions helped fixed my original code, but I think I'm better off with the list approach suggested by @Ananta – Paul Mar 03 '14 at 01:14
  • Hmm. Why? I think I prefer this solution -- computing on the language (i.e. `substitute()`) always seems to me to carry more potential complexities, so I avoid it unless I absolutely need it ... – Ben Bolker Mar 03 '14 at 01:44
  • Making a list of variable names and storing the data in a list of model objects seems to be easier to work with.. then I can use lapply to do things to each model in the list.. unless I am misunderstanding the approach you are suggesting? – Paul Mar 03 '14 at 03:46
0

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)

Community
  • 1
  • 1
Paul
  • 475
  • 8
  • 17