[R] Default argument not passed to subfunction when argument name matches default expression
Tierney, Luke
luke-tierney at uiowa.edu
Mon Mar 31 17:08:39 CEST 2014
Compiled code gives a better error message (not clear why the
interpreter doesn't do this as well):
> cmpfun(foo)()
Error in bar() :
promise already under evaluation: recursive default argument reference or ear$
The environment in which default arguments are evaluated is the
environment of the function call itself, not the environment of the
caller or the lexical enclosure (the same here). So the two 'y' used
in function(y = y) refer to the same binding, hence circular
reference. If you use
foo <- function (z = 2) {
bar <- function (y = z) y^2
bar()
}
then there is no problem:
> foo()
[1] 4
> cmpfun(foo)()
[1] 4
Best,
luke
Luke Tierney
Chair, Statistics and Actuarial Science
Ralph E. Wareham Professor of Mathematical Sciences
University of Iowa Phone: 319-335-3386
Department of Statistics and Fax: 319-335-3017
Actuarial Science
241 Schaeffer Hall email: luke-tierney at uiowa.edu
Iowa City, IA 52242 WWW: http://www.stat.uiowa.edu
________________________________________
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] on behalf of Philippe Grosjean [phgrosjean at sciviews.org]
Sent: Monday, March 31, 2014 9:40 AM
To: R Help
Subject: [R] Default argument not passed to subfunction when argument name matches default expression
Hello,
I have difficulties to understand this one:
foo <- function (y = 2) {
bar <- function (y = y) y^2
bar()
}
foo()
#! Error in y^2 : 'y' is missing
foo(3)
#! Error in y^2 : 'y' is missing
Note that this one works:
foo <- function (y = 2) {
bar <- function (y = y) y^2
bar(y) # Not using default value for y= argument
}
foo()
#! [1] 4
foo(3)
#! [1] 9
… as well as this one:
foo <- function (y = 2) {
bar <- function (Y = y) Y^2
bar() # Default, but different names for argument Y= and value 'y'
}
foo()
#! [1] 4
foo(3)
#! [1] 9
Best,
PhG
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list