[R] get: problem with environments
tramni at abv.bg
Fri Oct 12 11:13:02 CEST 2012
Dear Prof. Lumley,
Thank You very much for Your reply. I implemented Your idea
not to directly call get from sapply, but inside a function, supplied to sapply.
In this way the 3-rd parent frame is always the "correct" one, no matter whether I invoke testfun2()
all by itself or inside another function. So my code is finally stable.
It is quite tricky that when I call get() directly from sapply(), like this:
sapply(X=, FUN=get, envir=parent.frame()), actually envir is an argument not to get, but to
sapply, so it is evaluated in the environment of the caller, i.e. in the
environment of testfun1, whose parent is the workspace, which of course does not
contain the variables in the body of testfun1. In testfun2() sapply() calls get()
from within a function and the envir argument to get() is supplied directly to it, i.e.
it is evaluated in the environment of get(). Its first parent is the environment of the function calling get(), its second parent is the environment of sapply() and its third parent is the environment of testfun2(), which I need. That is why testfun2() works.
I hope I have correctly understood this matter. Please correct me if I am wrong.
Nevertheless the code is finally stable and it is thanks to Your suggestion.
>-------- Оригинално писмо --------
>От: Thomas Lumley
>Относно: Re: [R] get: problem with environments
>До: R. Michael Weylandt
>Изпратено на: Четвъртък, 2012, Октомври 11 01:52:14 EEST
>On Thu, Oct 11, 2012 at 11:18 AM, R. Michael Weylandt
>> Thanks Prof Lumley,
>> I'm still not sure how this gets to the call stack of 5 or 6 the OP
>> reported or the difference between GUI & Terminal. Any thoughts there?
>I don't see how the terminal version is getting 5 and 6 rather than 1
>and 2, but my testfun2() lets the OP do what he was originally trying
>The difference between testfun() and print(testfun()) (ie, 1 vs 2, or
>5 vs 6) is because of lazy evaluation: in print(testfun()), testfun()
>is called from inside print() when it needs the value to do method
>I can't reproduce the value of 5, so I can't help much. For anyone
>wanting to experiment further, it would probably be simpler to use
>rather than looking at whether a variable is found or not. I can't
>see how testfun() typed at the global command prompt can return
>anything other than 1, but maybe something is getting in between the
>console and the evaluator. For example:
> " 6"
>I don't see why a pure console program should do this on Linux, though.
>Professor of Biostatistics
>University of Auckland
More information about the R-help