Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

r - When/how/where is parent.frame in a default argument interpreted?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...