4

Truth be told, I'm just being lazy here, but perhaps someone could someday profit from the answer being here.

Say I define a function like:

fn<-function(envir=parent.frame())
{
    #do something with envir
}

My question is: what might I expect to be the content of envir?

Context: I had a rather long function f1 that contained a call to parent.frame. Now, I want to extract part of that function (containing the parent.frame call) into a new helper function f2 (which will then be called by f1), and I want to be sure that f1 does the same as it did before.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Nick Sabbe
  • 11,684
  • 1
  • 43
  • 57

1 Answers1

3

Default arguments are evaluated within the evaluation frame of the function call, from which place parent.frame() is the calling environment. envir's value will thus be a pointer to the environment from which fn was called.

Also, just try it out to see for yourself:

debug(fn)
fn()
# debugging in: fn()
# debug at #2: {
# }
Browse[2]> envir
# <environment: R_GlobalEnv>
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • 2
    Nice answer, but I don't think evaluation frame is well defined - I think local environment is more clear. – hadley Mar 19 '13 at 20:50
  • @hadley -- Nice suggestion, thanks. In the future, I'll probably go with either that or "environment of the current evaluation". – Josh O'Brien Mar 19 '13 at 22:42
  • 1
    Thanks. Very interesting. So that means that in this case, there would be quite a difference between calling $fn(parent.frame())$ and $fn()$, right? – Nick Sabbe Mar 20 '13 at 08:51
  • @NickSabbe -- Yes, exactly! `fn <- function(envir=parent.frame()) print(envir); g <- function() fn(); h <- function() f(parent.frame()); g(); h()`. – Josh O'Brien Mar 20 '13 at 13:24