Thanks to Andy Liaw, Roger Peng, Thomas Lumley, Brian Ripley and Peter
Dalgaard, all of whom addressed my questions or threads arising from
them.  The full messages were posted to the list so this is a brief
summary:

Andy Liaw explained the difference between lexical and dynamic scoping
and the rationale behind the choice of lexical scoping for R.  Roger
Peng showed how to modify fnB.  Brian Ripley suggested that it is
generally better to pass functions an object rather than just the name,
and warned of the dangers of using get() on the result of
deparse(substitute()).

Thanks all

Peter Alspach


Original question below:

I'm using R1.7.1 (Windows 2000) and having difficulty with scoping. 
I've studied the FAQ and on-line manuals and think I have identified
the
source of my difficulty, but cannot work out the solution.

For the purposes of illustration.  I have three functions as defined
below:

fnA <- function(my.x)
{
  list(first=as.character(substitute(my.x)), second=sqrt(my.x))
}

fnB <- function(AA)
{
  tmp.x <- get(AA$first)
  tmp.x^2
}

fnC <- function()
{
  x <- 1:2
  y <- fnA(x)
  z <- fnB(y)
  c(x,y,z)
}

fnA() has a vector as an argument and returns the name of the vector
and the square root of its elements in a list.  fn(B) takes the result
of fn(A) as its argument, gets the appropriate vector and computes the
square of its elements.  These work fine when called at the command
line.

fnC() defines a local vector x and calls fnA() which operates on this
vector.  Then fnB() is called, but it operates on a global vector x in
GlobalEnv (or returns an error is x doesn't exist there) - but I want
it
to operate on the local vector.

I think this is related to the enclosing environment of all three
functions being GlobalEnv (since they were created at the command
line),
but the parent environment of fnB() being different when invoked from
within fnC().

My questions:

1  Have I correctly understood the issue ?
2  How do I make fnB() operate on the local vector rather than the
global one ?
3  And, as an aside, I have used as.character(substitute(my.x)) to
pass
the name - but deparse(substitute(my.x)) also works.  Is there any
reason to prefer one over the other?

Thank you ...........



______________________________________________________
The contents of this e-mail are privileged and/or confidenti...{{dropped}}

______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to