Skip to content
Prev 307594 / 398506 Next

get: problem with environments

On Thu, Oct 11, 2012 at 9:05 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
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)))
 }

 testfun1(x1=1);

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

 testfun2(x1=1);


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.