[R] nested calls, variable scope

Jacob Wegelin jwegelin at vcu.edu
Thu Jul 17 22:54:30 CEST 2008


Below is an example of a problem I encounter repeatedly when I write functions.  A call works at the command line, but it does not work inside a function, even when I have made sure that all required variables are available within the function. The only way I know to solve it is to make the required variable global, which of course is dangerous. What is the elegant or appropriate way to solve this?


# The call to ns works at the command line:

> junk<-ns(DAT$Age, knots=74)

# The call to lmer works at the command line, with the call to ns nested within it:

> junk2<-lmer(formula=Finished ~ Sex01 + ns(DAT$Age, knots= 74 ) + MinCC + PzC + (1 | NAME ) + (1 | Year), data=myDATonly, family="binomial")

But now I want to do this within a function such as the following:

> myfn
function(myknot=74) {
         library(lme4)
         library(splines)
         cat("myknot=", myknot, "\n")
         myMER<-lmer(formula=Finished ~ Sex01 + ns(DAT$Age, knots= myknot) + MinCC + PzC + (1 | NAME ) + (1 | Year), data=myDATonly, family="binomial")
}

> myfn(74)
myknot= 74 
Error in ns(DAT$Age, knots = myknot) : object "myknot" not found

# The bad way to do it: revise myfn to make myknot a global variable:
> myfn
function(myknot=74) {
         library(lme4)
         library(splines)
         cat("myknot=", myknot, "\n")
         myknot<<-myknot
         myMER<-lmer(formula=Finished ~ Sex01 + ns(DAT$Age, knots= myknot
) + MinCC + PzC + (1 | NAME ) + (1 | Year), data=myDATonly,
family="binomial")
}

> z<-myfn(74)
myknot= 74

# Runs fine but puts a global variable into .GlobalEnv.


> sessionInfo()
R version 2.6.2 (2008-02-08) 
i386-pc-mingw32

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

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

other attached packages:
[1] lme4_0.999375-13  Matrix_0.999375-9 lattice_0.17-6

loaded via a namespace (and not attached):
[1] boot_1.2-32 grid_2.6.2 
>

Thanks for any insight.

Jacob A. Wegelin
jwegelin at vcu.edu 
Assistant Professor
Department of Biostatistics
Virginia Commonwealth University
730 East Broad Street Room 3006
P. O. Box 980032
Richmond VA 23298-0032
U.S.A. 
http://www.people.vcu.edu/~jwegelin



More information about the R-help mailing list