[R] get: problem with environments

Thomas Lumley tlumley at uw.edu
Wed Oct 10 23:04:51 CEST 2012

On Thu, Oct 11, 2012 at 9:05 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> Can someone more capable than I help Martin out with this? I'm feeling
> out of my league (that or I've missed something obvious)
> Shot in the dark: you aren't running this in some sort of debug mode, are you?
> On Sun, Oct 7, 2012 at 5:10 PM, Martin Ivanov <tramni at abv.bg> wrote:
>>  Thank You very much for Your replies.
>> Dear Michael,
>> "Does this persist after a new session (perhaps running as R --vanilla) and/or reinstall?"
>> Yes, it does. After running R --vanilla, still there are 4 contexts more on the call stack.
>> "You didn't show us how you tried to use parent.frame()"
>> I did it like this:
>> testfun1 <- function (x1) {
>>  a1 <- 1;
>>  sapply(X="a1", FUN=get, envir=parent.frame(x1));
>> }
>> testfun1(x1=1);
>> The above code never succeeds no matter what a number I give to x1.

This one is straightforward.

The smallest value you can give to parent.frame() is 1, which in this
case is the frame from which testfun1 is called.  Compare these two

testfun1 <- function (x1) {
 	a1 <- 1
 	sapply(X="a1", FUN=get, envir=parent.frame(x1)))


testfun2 <- function (x1) {
 	a1 <- 1
 	sapply(X="a1", FUN=function(x) get(x, envir=parent.frame(x1)))


testfun1() never finds a1==1, but testfun2(3) does.

Remember, actual arguments to sapply() will be evaluated in the frame
sapply() is called from.  It's only default arguments that are
evaluated inside the function.

Thomas Lumley
Professor of Biostatistics
University of Auckland

More information about the R-help mailing list