[R] Default argument not passed to subfunction when argument name matches default expression

Duncan Murdoch murdoch.duncan at gmail.com
Mon Mar 31 16:58:39 CEST 2014


On 31/03/2014 10:40 AM, Philippe Grosjean 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

This is simply a misunderstanding about scoping.  The default value for 
a function argument is evaluated in the local frame, not the caller 
frame, so specifying an argument as y = y is not a useful thing to do.

Duncan Murdoch

>
> 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