默认函数参数值在 R 中被延迟评估(即仅在需要时评估):
查看此代码的输出以获取示例:
printme <- function(name,x){cat('evaluating',name,'\n');x}
h <- function(a = printme('a',1), b = printme('b',d)){
cat('computing d...\n')
d <- (a + 1)^2
cat('d computed\n')
cat('concatenating a and b...\n')
c(a, b)
cat('a and b concatenated\n')
}
h()
控制台输出:
computing d...
evaluating a
d computed
concatenating a and b...
evaluating b
a and b concatenated
如您所见,d 是在评估 b 的默认值之前计算出来的
编辑:
此外,正如 @BrodieG 在 cmets 中正确指出的,默认参数在函数环境中进行评估;事实上,在上面的例子中,b 可以初始化为函数环境中定义的变量d 的值。
相反,当你指定一个参数(不使用默认值)时,分配参数的表达式仍然是惰性计算的,但这次是在调用环境中,例如:
# same functions as above, but this time we specify the parameters in the call
h(a=printme('a',123),b=printme('d',d))
控制台输出:
computing d...
evaluating a
d computed
concatenating a and b...
evaluating d
Error in printme("d", d) : object 'd' not found
请注意在评估参数 b 时的错误,因为在调用环境中找不到 d。