[R] get: problem with environments

Martin Ivanov tramni at abv.bg
Sun Oct 7 11:16:42 CEST 2012


 Dear R users,

I am running R-2.15.1 in Linux Slackware64-14.0. Here is my minimal working example:

testfun <- function (x) {
 a <- 0;
 sapply(X="a", FUN=get, envir=sys.frame(which=x));
}

Inside R, that is R called from within a Linux terminal, the following code works:
testfun(x=5)
print(testfun(x=6))
But within rkward the above code fails and the following works:
testfun(x=1)
print(testfun(x=2))

As you can see, the number of contexts up the call stack that contain the variable "a"
varies depending on the implementation. If I call testfun() from within print(), I have to go 
one context up the call stack than if I call testfun() alone by itself. This implies 
some inherent instability of my code. 

Actually I need to provide get() access to the calling environment of sapply().
According to the documentation of parent.frame(), "The parent frame of a function evaluation is the environment in which the function was called". I tried to use parent.frame() instead of sys.frame() above,
but the variable "a" is never found, regardless of what value I give to the parameter "n" of 
parent.frame().

I have basically three questions:

1. Do You have an idea how I could implement the code 
more stably, so that the variable "a" is always visible to get, regardless of whether testfun
is used alone by itself or called from within another function?

2. Why does the implementation with parent.frame() not work?

3. Why does the number of contexts in the call stack differ in R and in rkward? It seems that when R is called from within the Linux terminal the call stack contains 4 contexts more that it does when is called from rkward. This also points to the instability of the code which I would like to solve.

Any suggestions on any on the above questions will be greatly appreciated.

Best regards,

Martin



More information about the R-help mailing list