parenthesis for R function -


i reading hadley wickham's book "advanced r" , came across following code.

`(` <- function(e1) { if (is.numeric(e1) && runif(1) < 0.1) { e1 + 1 } else { e1 } } 

i follwing output when running function

> (1) [1] 1 > (1) [1] 2 

q: why (1) run above function rather ((1) ?

i tried below,

f <- function(e1){if (is.numeric(e1) && runif(1) < 0.1) { e1 + 1 } else { e1 } }  > f(1) [1] 2 > f1) error: unexpected ')' in "f1)" 

you can check definition of ( in r:

> `(` .primitive("(") 

now construct function ( in global environment (that's hadley if run code @ console). when r looks function, uses search path starts in global environment. hence first finds function definition of hadley. why keeps working.

the second part of explanation r interpreter itself. if sees symbol ( (but [ or + or other special operator) looks function name , "rearranges" arguments. example, a + b "rearranged" as:

call `+` first argument , second argument b 

and (anexpression) "rearranged" as"

call `(` anexpression argument 

but afun(alistofarguments) interpreted as:

call afun alistofarguments list of arguments 

in case ( not function rather part of syntax calling function. 2 different things.

so ((1) or f1) can't work,

`(`(1)  

does. because when r interpreter sees ( automatically looks closing ) complete syntax, when sees

`(` 

it knows you're refering function named (.

disclaimer: explanation conceptual, technical details of r interpreter bit more complex.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -