[Rd] why does parent.frame() cycle when called from inside capture.output()?

frederik at ofb.net frederik at ofb.net
Mon Dec 12 06:54:41 CET 2016


Hello R devel/help,

I ran into this strange behavior:

    # showstack is supposed to walk through the stack of parent
    # environments when it is called:
    showstack = function() {
      env = environment()
      for(i in 1:12) {
        env = do.call(parent.frame, list(), env=env)
        print(env)
      }
    }

    # a simple chain of functions:
    g3=function(t) showstack()
    g2=function(w) g3(w)
    g1=function(z) g2(z)
    g=function(y) g1(y)

    g()
    # outputs:
    # <environment: 0xb5ef810>
    # <environment: 0xb5ef6f8>
    # <environment: 0xb5ef5e0>
    # <environment: 0xb5ef4c8>
    # <environment: R_GlobalEnv>
    # <environment: R_GlobalEnv>
    # <environment: R_GlobalEnv>
    # <environment: R_GlobalEnv>
    # <environment: R_GlobalEnv>
    # ...

    cat(capture.output(g()),sep="\n")
    # outputs:
    # <environment: 0x8106a30>
    # <environment: 0x8106918>
    # <environment: 0x8106800>
    # <environment: 0x81066e8>
    # <environment: R_GlobalEnv>
    # <environment: 0x8107458>
    # <environment: 0x81071b8>
    # <environment: 0x80c6a08>
    # <environment: R_GlobalEnv>
    # <environment: 0x8107458>
    # <environment: 0x81071b8>
    # <environment: 0x80c6a08>

The strange thing of course is that the second call doesn't stay with
R_GlobalEnv, but in fact goes into a loop of period 4. I'm not so
surprised that the parent frame of the global environment is itself,
as in the first call, but it seems weird to have a loop of period 4...
Using `ls()` shows that two of the "loop" environments belong to
capture.output() and eval().

But if capture.output is really evaluating its input in the parent
frame, as it appears to be doing from its source code, then I would
have expected the output to be the same as the output I get by
evaluating the same expression in this frame.

I was trying to debug a function which attempts to be a multi-frame
version of deparse(substitute(...)). I'm attaching this function in
case anyone is curious. Perhaps my attachment can shed more light on
the problem I'm having.

Apologies if this is not a bug - I wasn't sure which mailing list to
send this to, and I took a guess.

Thanks,

Frederick
-------------- next part --------------
desubN <- function(y,n=1) {
  env=environment();
  for(i in 1:n) {
    y = do.call(substitute, list(substitute(y)), env=env)
    env = do.call(parent.frame, list(), env=env)
  }
  deparse(y)
}
g2=function(t) {
  for(i in 1:5) {
    print(desubN(t,i))
    print(capture.output(desubN(t,i)))
  }
}
g1=function(z) g2(z)
g=function(y) g1(y)

g(log)
# output: (why does it stop at "z"?)
## [1] "t"
## [1] "[1] \"t\""
## [1] "z"
## [1] "[1] \"z\""
## [1] "y"
## [1] "[1] \"z\""
## [1] "log"
## [1] "[1] \"z\""
## [1] "log"
## [1] "[1] \"z\""


More information about the R-devel mailing list