Oh No
Oh No

Reputation: 165

parenthesis for R function

I am reading Hadley Wickham's book "Advanced R" and came across the following code.

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

I get the follwing output when running the function

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

Q: why does (1) run the above function rather than ((1) ?

I also tried the 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)"

Upvotes: 3

Views: 147

Answers (1)

Joris Meys
Joris Meys

Reputation: 108523

You can check the definition of ( in R:

> `(`
.Primitive("(")

Now you construct a function ( in the global environment (that's what Hadley actually does if you run that code at the console). When R looks for a function, it uses a search path that starts in the global environment. Hence it first finds the function definition of Hadley. That is why it keeps working.

The second part of the explanation is the R interpreter itself. If it sees a symbol like ( (but also [ or + or any other special operator) it looks for a function with that name and "rearranges" the arguments. For example, a + b will be "rearranged" as:

call `+` with first argument a and second argument b

and (anExpression) will be "rearranged" as"

call `(` with anExpression as only argument

but aFun(aListofArguments) is interpreted as:

call aFun with aListofArguments as the list of arguments

In this case ( is not so much a function but rather part of the syntax for calling a function. Those are two different things.

So ((1) or your f1) can't work, but

`(`(1) 

does. Because when the R interpreter sees ( it automatically looks for the closing ) to complete the syntax, but when it sees

`(`

it knows you're refering to a function named (.

Disclaimer: this explanation is conceptual, the technical details of the R interpreter are obviously a bit more complex.

Upvotes: 7

Related Questions