[R] Default argument not passed to subfunction when argument name matches default expression
Bert Gunter
gunter.berton at gene.com
Mon Mar 31 17:12:48 CEST 2014
Note that the fact that bar() is defined within foo() is irrelevant.
## At the top level/global prompt:
> y <- 2
> bar<- function(y=y)y^2
> bar()
Error in y^2 : 'y' is missing
## but
> bar(y)
[1] 4
This is due to lazy evaluation and promises: The formal argument "y"
is not evaluated until it's used in "y^2" . But if called without an
argument, the default is evaluated **within the function
environment**, and y is missing there. When an explicit argument is
given in the call, it is evaluated in the environment in which the
function is called, the Global environment, where y has been defined.
Similar arguments explain your example.
Cheers,
Bert
Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374
"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch
On Mon, Mar 31, 2014 at 7:40 AM, Philippe Grosjean
<phgrosjean at sciviews.org> wrote:
> 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