[R] nested calls, variable scope

From: Jacob Wegelin <jwegelin_at_vcu.edu>
Date: Thu, 17 Jul 2008 16:54:30 -0400 (EDT)

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) {

         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) {

         cat("myknot=", myknot, "\n")
         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)

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
Assistant Professor
Department of Biostatistics
Virginia Commonwealth University
730 East Broad Street Room 3006
P. O. Box 980032
Richmond VA 23298-0032

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 17 Jul 2008 - 20:57:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 17 Jul 2008 - 21:32:45 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive