[R] Is function(x){x}(5) a valid expression?
Duncan Murdoch
murdoch.duncan at gmail.com
Tue Nov 13 20:19:33 CET 2012
On 13/11/2012 1:33 PM, Jamie Olson wrote:
> I was surprised to notice that statements like:
>
> h = function(...){list(...)}(x=4)
>
> do not throw syntax errors. R claims that 'h' is now a function, but I
> can't seem to call it.
>
> > h = function(x){list(x)}(4)
> > is(h)
> [1] "function" "OptionalFunction" "PossibleMethod"
> > h()
> Error in list(x) : 'x' is missing
> > h(4)
> Error in h(4) : attempt to apply non-function
> >
>
> What's going on?
The body of your function is
{list(x)}(4)
The problem is,
{list(x)}
does not return a function, so you can't call it with the argument 4.
If you had
h <- function(x) { function(y) y }(4)
it would return 4 every time, because the anonymous function does that.
Duncan Murdoch
More information about the R-help
mailing list