[R] Scoping rules

Roger D. Peng rpeng at jhsph.edu
Thu Oct 9 03:07:28 CEST 2003


It seems like you want in fnB

get(AA$first, envir = parent.frame(1))

but I'm entirely clear on why your original function doesn't work.  My 
understanding was that get() should search through the parent frames.

-roger

Peter Alspach wrote:
> Dear List members:
> 
> 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 ...........
> 
> 
> Peter Alspach
> 
> 
> 
> ______________________________________________________
> The contents of this e-mail are privileged and/or confidential to the
> named recipient and are not to be used by any other person and/or
> organisation. If you have received this e-mail in error, please notify 
> the sender and delete all material pertaining to this e-mail.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>




More information about the R-help mailing list