While attempting to re-run some previously working code this morning, I
seem to have stumbled upon a bug in how lmer() works with update(). For
some reason, when I try to update a glmer or lmer model within a function,
lmer() or update() can only see a dataframe if it is in the global
environment. I have included an example below (a similar script written for
glm works fine). Any ideas on how to correctly specify the environment so I
can get around this?

Thanks for your help

James Forester

Platform: x86_64-pc-linux-gnu
R version: 2.15.2 (2012-10-26)
lme4 version: 0.999999-0



###########################
## Test function
###########################

testlmer<-function(dat1, test.update=TRUE, save.global=FALSE){

  if(save.global){
    dat1<<-dat1
  }

  ##This model borrowed from the examples in ?lmer
  basemod=glmer(cbind(incidence, size - incidence) ~ period + (1 | herd),
                family = binomial, data = dat1)

  if(test.update){
    ##This is where the problem seems to be
    update.mod=update(basemod,.~. + rand.dat)
    return(update.mod)
  }else return(basemod)
}

###########################
## Test script
###########################
library(lme4)

##add a spurious column of data
cbpp$rand.dat = rnorm(nrow(cbpp))

## this works: a glmer model is fit within the function
##   and is then updated in the global environment
testmod = testlmer(cbpp, test.update=FALSE, save.global=FALSE)
testmod = update(testmod,.~. + rand.dat,data=cbpp)

## this fails: attempting to update the base model,
##   the function fails with "object 'dat1' not found"
##   In this case 'dat1' is only within the function environment
testmod = testlmer(cbpp, test.update=TRUE, save.global=FALSE)

## this works: here the data are saved to the global environment
##    before the model update
testmod = testlmer(cbpp, test.update=TRUE, save.global=TRUE)
rm(dat1)

	[[alternative HTML version deleted]]

