[R] Using lme() inside a function (should be: stepAIC from lme inside function)

Dieter Menne dieter.menne at menne-biomed.de
Fri May 9 15:55:34 CEST 2008


ONKELINX, Thierry <Thierry.ONKELINX <at> inbo.be> writes:

> This solutions works with R 2.7.0 under windows
> 
> library(MASS)
> library(nlme)
> PredRes <- function(cal, val){
>     cal <<- cal
>     lmemod <- lme(distance ~ age * Sex, random = ~1|Subject, data = cal,
> method="ML")
>     themod <- stepAIC(lmemod, dir="both", trace = FALSE)
>     prs <- predict(themod, newdata = val)
>     obs <- val$distance
>     print(mean(obs - prs))
> }
> 
> PredRes(cal = subset(Orthodont, age!=14), val = subset(Orthodont,
> age==14))
>  obs<-subset(Orthodont,age==14)$distance
> > print(mean(obs-prs))

That's a workaround, but it effectively makes cal global, and so should be
considered not so nice programming practice. The problem is an environment
problem in stepAIC, and I am sure Brian Ripley will tell us what's wrong...

10: inherits(x, "data.frame")
9: is.data.frame(data)
8: lme.formula(fixed = distance ~ age + Sex, data = D1, random = ~1 | 
       Subject, subset = age != 14, method = "ML")
7: eval(expr, envir, enclos)
6: eval(expr, p)
5: eval.parent(nfit)
4: dropterm.default(fit, scope$drop, scale = scale, trace = max(0, 
       trace - 1), k = k, ...)
3: dropterm(fit, scope$drop, scale = scale, trace = max(0, trace - 
       1), k = k, ...)
2: stepAIC(lmemod, dir = "both")
1: PredRes(Orthodont)


R version 2.8.0 Under development (unstable) (2008-05-03 r45596) 
i386-pc-mingw32 

locale:
LC_COLLATE=German_Germany.1252;LC_CTYPE=German_Germany.1252;
LC_MONETARY=German_Germany.1252;LC_NUMERIC=C;LC_TIME=German_Germany.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] nlme_3.1-88 MASS_7.2-42

loaded via a namespace (and not attached):
[1] grid_2.8.0     lattice_0.17-7 tools_2.8.0   
> 

Dieter



More information about the R-help mailing list