wrapper <-function(WhichApproach=1, splineDF=4 ){ # Create toy dataset nID<-25 IDnames<-LETTERS[1:nID] longdat<-data.frame( x=rep(-10:10, nID) / 3 , ID= rep( IDnames , each=21) ) set.seed(5) longdat$x<-longdat$x + rnorm(nrow(longdat))/10 IDeffect<-rnorm(nID) * 20 names(IDeffect) <- IDnames longdat$IDeffect<-IDeffect[as.character(longdat$ID)] longdat$y<- (longdat$x + longdat$x^3 + (longdat$x-1)^4 / 5 + 1/(abs(longdat$x/50) + 0.02) + longdat$IDeffect + rnorm(1:nrow(longdat)) * 2 ) longdat<-longdat[order(longdat$x),] library(splines) # Calling ns within lm works fine: mylm<- lm( y ~ ns(x,df=splineDF), data=longdat) longdat$lmfit<-predict(mylm) library(ggplot2) print( ggplot(longdat, aes(x, y)) + geom_point(shape=1) + geom_line(aes(x=x, y=lmfit), color="red") ) cat("Enter to attempt lme.") readline() library(nlme) if(WhichApproach==1) { # returns: "Error in eval(expr, envir, enclos) : object 'splineDF' not found" # # First make sure splineDF does not exist in .GlobalEnv, else we would be in WhichApproach==2. if(exists("splineDF", where=".GlobalEnv")) remove(list="splineDF", pos=".GlobalEnv") mylme<-lme(fixed= y ~ ns(x, df=splineDF) , random= ~ 1 | ID , correlation = corAR1() , data=longdat ) } else if(WhichApproach==2) { # returns: "Error in model.frame.default(formula = ~ID + y + x + splineDF, data = list( : # variable lengths differ (found for 'splineDF')" assign(x="splineDF", value=splineDF, pos=".GlobalEnv") mylme<-lme(fixed= y ~ ns(x, df=splineDF) , random= ~ 1 | ID , correlation = corAR1() , data=longdat ) } else if (WhichApproach==3) { thecommandstring<- paste("mylme<-lme(fixed= y ~ ns(x, df=", splineDF, ") , random= ~ 1 | ID , correlation = corAR1() , data=longdat)") thecommandstring eval(parse(text=thecommandstring)) } else { stop(paste("WhichApproach=", WhichApproach, " not valid.")) } mylme longdat$fullfit<-predict(mylme) library(ggplot2) print( ggplot( longdat, aes(x,y)) + geom_point(shape=1) + facet_wrap( ~ ID ) + geom_line( aes(x, fullfit), color="red") ) invisible(mylme) }