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

William Dunlap wdunlap at tibco.com
Tue Nov 13 20:12:01 CET 2012


The syntax
    expression(arg)
means to call the value of 'expression' as a function with argument 'arg'.
Hence you can do things like
   { function(x)x^2 } (11:13) # gives 121, 144, 169
or, weirder,
   eval(call("function", pairlist(x=NULL, base=2), quote(log(x,base)))) (512) # gives 9

If 'expression' is not a function you get an error of the sort you saw, similar
to what you would get if you did
   x <- 1:10
   x(17)
The parser doesn't know if 'expression' will evaluate to a function or not
so it accepts it and you get the error at run time.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Jamie Olson
> Sent: Tuesday, November 13, 2012 10:33 AM
> To: r-help at r-project. org
> Subject: [R] Is function(x){x}(5) a valid expression?
> 
> 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?
> 
> Jamie Olson
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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