I'm trying to write a function that calculates the R^2 from a generalized linear mixed model in R using glmer. Somehow as soon as try to use the function I get an error:
Error in checkFormulaData(formula, data, checkLHS = control$check.formula.LHS == : bad 'data': object 'input_data' not found
If I use the same code without a function everything is fine. To test if there was an general problem with r.squaredGLMM within functions I also created a function for a linear mixed model, which is working as expected.
Here is a reproducible example:
library(lme4)
library(MuMIn)
#Generate some sample data
x <- rnorm(100)
y1 <- sample(c(0,1), 100, replace = TRUE)
y2 <- rnorm(100)
subject <- rep(1:10, 10)
df <- data.frame(x,y1,y2,subject)
#Calculate glmer and get the R^2
mod1_outside_function <- glmer(y1 ~ x + (1|subject), data = df,family="binomial")
#Works just fine
R2 <- r.squaredGLMM(mod1_outside_function)
print(R2)
#Create a function to get the R2
R2_glmer <- function(input_data)
{
glmer_inside_function <- glmer(y1 ~ x + (1|subject), data = input_data,family="binomial")
R2 <- r.squaredGLMM(glmer_inside_function)
print(R2)
}
#I get the error running this:
R2_glmer(input_data = df)
#The same function works with lmer:
R2_lmer <- function(input_data)
{
lmer_inside_function <- lmer(y2 ~ x + (1|subject), data = input_data)
R2 <- r.squaredGLMM(lmer_inside_function)
print(R2)
}
R2_lmer(input_data = df)
It is a bug with evaluation of the null model in non-global environments. It should work now with MuMIn version >=1.42.4 (on R-forge currently). To work it around, you can provide the null model as a second argument:
r.squaredGLMM(glmer_inside_function, null.fit(glmer_inside_function, RE.keep = TRUE, evaluate = TRUE))