Hi,
I'm struggling with a bit of scoping using the with() function. I think it's best explained with an example:
x <- list(foobar=2)
f <- function(){foobar*2}
with(x,f())
This throws an error that 'foobar' does not exist. However if I define foobar in the global environment, f will find it whether I call it from the global environment or from within x. I have also tried using get("foobar",parent.frame()) within f, along with other variations, with no success.
I could always just add foobar as an argument to f, but in my actual work case foobar is a potentially very large object that is not worth making a copy of. (I don't know how much of an effect this will actually have on performance). I also just don't like all the bookkeeping of having to know which objects in x I am going to need in f and passing them all as arguments.
I would appreciate any insight about why the scoping is not working as I thought it would, and if there is any way to get around it without directly passing arguments to f.
Thank you,
Peter
Scoping question
2 messages · iuhz7j202 at sneakemail.com, Simon Urbanek
Peter, this is a list for Mac-related issues. Please use R-help for general questions for help - or actually just read about the difference between lexical and dynamic scoping (R uses the former which means that f will be evaluated in the global environment so there will be no foobar). Cheers, Simon
On Apr 14, 2009, at 12:08 , iuhz7j202 at sneakemail.com wrote:
Hi,
I'm struggling with a bit of scoping using the with() function. I
think it's best explained with an example:
x <- list(foobar=2)
f <- function(){foobar*2}
with(x,f())
This throws an error that 'foobar' does not exist. However if I
define foobar in the global environment, f will find it whether I
call it from the global environment or from within x. I have also
tried using get("foobar",parent.frame()) within f, along with other
variations, with no success.
I could always just add foobar as an argument to f, but in my actual
work case foobar is a potentially very large object that is not
worth making a copy of. (I don't know how much of an effect this
will actually have on performance). I also just don't like all the
bookkeeping of having to know which objects in x I am going to need
in f and passing them all as arguments.
I would appreciate any insight about why the scoping is not working
as I thought it would, and if there is any way to get around it
without directly passing arguments to f.
Thank you,
Peter
_______________________________________________ R-SIG-Mac mailing list R-SIG-Mac at stat.math.ethz.ch https://stat.ethz.ch/mailman/listinfo/r-sig-mac