[R] I don't understand this
Richard A. O'Keefe
ok at cs.otago.ac.nz
Wed Sep 3 04:34:51 CEST 2003
"Simon Fear" <Simon.Fear at synequanon.com> wrote:
But seriously, I am sure Richard O'K had no intention of doing
any such thing. The question was just about the syntax of R, no?
Exactly so.
Isn't it the case that
(expr)(expr)
is incorrect syntax under any circumstances?
No.
Functions are values in R, just like they are in C and Scheme.
And R accepts expressions in function position, just as C and Scheme do.
> (sqrt)(4)
[1] 2
> f <- c(sin,cos)
> f[[1]](0)
[1] 0
> f[[2]](0)
[1] 1
Beware: f[1] and f[2] are lists, not functions; they don't work.
> (if (TRUE) cos else sin)(0)
[1] 1
> (if (FALSE) cos else sin)(0)
[1] 0
Not only is this all allowed by R's parser, it works just fine.
Why _should_ it be a syntax error?
There's one difference between f(x) and (f)(x).
The first is basically
get("f", mode="function")(x)
while the second is basically
get("f", mode="any")(x).
A couple of times this has kept me out of trouble when I've
unwittingly used c as a local numeric variable AND as the
column constructor function. I'm not entirely sure that I'm
grateful for this; I never _meant_ to do any such thing and
I'd rather have been told about my mistake. But that interpretation
of f(x) is clearly described in the New S book.
More information about the R-help
mailing list