[R] Help with non standard evaluation and require function

peter dalgaard pdalgd at gmail.com
Sun Aug 14 11:46:59 CEST 2016


> On 14 Aug 2016, at 11:23 , Luca Cerone <luca.cerone at gmail.com> wrote:
> 
> I have no access to my laptop so I can't double check but I think in one of
> Wickham's book there was an example like
> 
> f <- function (y) {
>  substitute (x + y)
> }
> 
> f(4)
> [1] x + 4
> 
> i.e. where substitute inside a function was substituting the value of y and
> returned the expression replacing y with 4, which is what I would expect to
> happen.
> 

In a word: no.

> f <- function (y) {
+  substitute (x + y)
+ }
> 
> f(4)
x + 4
> f(z)
x + z

i.e., it is not the value of y, but the expression passed for y that gets substituted.

There are subtleties: If y is computed inside the function, the connection to the argument expression is lost, and then the value is in fact used:

> z <- pi
> f <- function (y) { y <- y
+  substitute (x + y)
+ }
> f(z)
x + 3.14159265358979

It is usually a better idea to handle these issues with bquote(), though.


-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list