R Notes

lme can't be used in a function

I tried to call lme from a function and found that it failed with "object not found" errors and did other stupid things, like always returning the same result in a loop. It turns out that lme uses the global environment and gets confused if you put it in a function with locally-scoped variables. The hack is to temporarily make your variable a global:

lmefunc <- function() {
   lmspecies <<- data[[foo]]
   lmmod <- lme(lmspecies ~ foo + bar, data = baz)
   rm(lmspecies, envir=globalenv())

Note the use of the <<- operator to assign in the global environment.