Reputation: 1629
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?
Upvotes: 5
Views: 3223
Reputation: 10215
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)
Upvotes: 2