[R] scope, lme, ns, nlme, splines

Jacob Wegelin jacobwegelin at fastmail.fm
Thu Dec 6 20:28:15 CET 2012


I want to fit a series of lme() regression models that differ only in the
degrees of freedom of a ns() spline. I want to use a wrapper function to do
this. The models will be of the form

y ~ ns(x, df=splineDF)

where splineDF is passed as an argument to a wrapper function.

This works fine if the regression function is lm(). But with lme(),
I get an error.  fitfunction() below demonstrates this.

Why?

KLUDGEfit() below provides a clumsy solution. It turns the lme()
command, along with the appropriate value of splineDF, into a text
string and then uses eval(parse(text=mystring)).  But is there not a
more elegant solution?

set.seed(5)
junk<-data.frame(x=rnorm(100))
junk$y<-junk$x + rnorm(nrow(junk))
junk$idvar<- factor(sample(LETTERS[1:10], size=nrow(junk), replace=TRUE))
library("nlme")
library(splines)

fitfunction<-function(splineDF=1) {
 	thislm<-lm( y ~ ns(x, df=splineDF), data= junk)
 	thislm
 	cat("finished thislm\n")
 	thislme<-lme(
 		fixed= y ~ ns(x, df=splineDF)
 		, random= ~ 1 | idvar
 		, data= junk)
 	thislme
}
fitfunction()

KLUDGEfit<-function(splineDF=2) {
 	thislm<-lm( y ~ ns(x, df=splineDF), data= junk)
 	thislm
 	cat("finished thislm\n")
 	mystring<-paste(
 	"thislme<-lme( fixed= y ~ ns(x, df="
 	, splineDF
 	, "), random= ~ 1 | idvar , data= junk)"
 	, sep="")
 	eval(parse(text=mystring))
 	thislme
}
KLUDGEfit()

Thanks for any insight

Jacob A. Wegelin
Assistant Professor
Department of Biostatistics
Virginia Commonwealth University
830 E. Main St., Seventh Floor
P. O. Box 980032
Richmond VA 23298-0032
U.S.A.



More information about the R-help mailing list