Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summary of lme4 model in function (lmerTest)

Tags:

r

summary

lme4

If one has the following data

d = data.frame(out=rnorm(10), explain=rnorm(10), age=rnorm(10), sex=sample(c("M", "F"), size=10, replace=T), group=rep(c(1:5), 2))
f = as.formula("out ~ explain + age + sex + (1|group)")

and wants to fit a linear model with lme4 you can do

require(lme4)
require(lmerTest)
m  = lmer(f, d)
s  = summary(m)

That works, good.... But if the model is fitted within another function like

gglm = function(form, data){
    lm = lmer(form, data=data)
    return(lm)
}
m2 = gglm(f, d)
s2 = summary(m2)

I get an error.

summary from lme4 is returned
some computational error has occurred in lmerTest

Apparently, this is because the fitting of the model was done with a object called data, which is not visible in the outer scope. So if I do data = d I get the same result as before. However, if I do

data = data.frame(out=rnorm(10), explain=rnorm(10), age=rnorm(10), sex=sample(c("M", "F"), size=10, replace=T), group=rep(c(1:5), 2))

instead and get different data, the result of the summary is wrong.

This seems not to be the best way to do it and i think its easy to make mistakes. The normal lm and its according summary functiondon't have this problem. Isn't there a way to make the lmerTest summary less error prone?

like image 411
Jonas Avatar asked Nov 01 '22 12:11

Jonas


1 Answers

The do.call trick works (but it is a workaround, for sure).

gglm = function(form, data){
  lm = do.call(lmer, list(formula=form, data=data))
  return(lm)
}
m2 = gglm(f, d)
s2 = summary(m2)
like image 96
Dieter Menne Avatar answered Nov 15 '22 05:11

Dieter Menne