R lmerTest step() inside custom function pulling data from global environment not function environment

30 views Asked by At

I am creating a custom function to do a backwards stepwise model selection method. This is a small part of a larger analysis, I do not need to debate the validity of stepwise model selection in this post.

The function is below. When I run it, the first two models work fine and their summaries are printed properly. But the stepwise model throws,

Error in eval(mf, parent.frame()) : object 'dat' not found

even though dat is defined in the function. I believe this is an issue with the step() function trying to use a dataframe from my global environment and not the function environment.

Is there a way to specify the environment for the step() function?

lmerstepFX <- function(datalongDF, analyte.string, dfname.string){
  
  datlong <- datalongDF
  analyte.s <- analyte.string
  dfname <- dfname.string
  
  dat <- datlong[datlong$analyte == analyte.s,]
  
  mm.0 <- lmer(data = dat,
               log(concentration) ~
                 (1|site),
               REML = F)
  print(summary(mm.0))
  
  mm.1 <- lmer(data = dat,
               log(concentration) ~ v1 + v2 + v3 +
                 (1|site),
               REML = F)
  print(summary(mm.1))
  
  mm.2.step <- step(mm.1)
  mm.2.step
  mm.2 <- get_model(mm.2.step)
  print(summary(mm.2))
  print(anova(mm.2))
  
}

I am not sure how to move forward, any support is greatly appreciated.

0

There are 0 answers