[R] Is function(x){x}(5) a valid expression?

Brian Diggs diggsb at ohsu.edu
Tue Nov 13 21:28:16 CET 2012


On 11/13/2012 11:19 AM, Duncan Murdoch wrote:
> 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.

Another way to see this is

 > body(h)
{
     list(x)
}(4)
 > eval(body(h))
Error in eval(expr, envir, enclos) : attempt to apply non-function

So the body is syntactically valid, but can not be evaluated because, as 
Duncan said, {list(x)} is not a function (and that fact can not be 
determined until it is being executed).

> If you had
>
> h <- function(x) { function(y) y }(4)
>
> it would return 4 every time, because the anonymous function does that.

If what you were doing is to create an anonymous function and 
immediately call it, you can do that as

h <- (function(x){list(x)})(4)

in which case

 > is(h)
[1] "list"   "vector"
 > h
[[1]]
[1] 4

I'm not sure which behavior you were expecting.

> Duncan Murdoch
>


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University




More information about the R-help mailing list