Bracket 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 am getting output output when running the function

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

      

Q: why (1) the above function is executed and not ((1)?

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

      

+3


source to share


1 answer


You can check the definition (

in R:

> `(`
.Primitive("(")

      

Now you are creating a function (

in the global environment (which is what Hadley actually does if you run this code on the console). When R searches for a function, it uses a search path that starts in the global environment. So he first finds the definition of the Hadley function. This is why it continues to work.

The second part of the explanation - is itself an interpreter R. If he sees a character like (

(but also [

, or +

, or any other specific operator), it looks for a function with the same name and "rearranges" arguments. For example, it a + b

will be "rebuilt" as:

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

      

and (anExpression)

will be "reordered" as "

call `(` with anExpression as only argument

      

but aFun(aListofArguments)

interpreted as:



call aFun with aListofArguments as the list of arguments

      

In this case (

, it is not so much a function as part of the syntax for calling a function. These are two different things.

So ((1)

or yours f1)

may not work, but

`(`(1) 

      

does. Because when the R interpreter sees (

it automatically looks for a closure )

to complete the syntax, but when it sees

`(`

      

it knows that you are referring to a function named (

.

Disclaimer: This explanation is conceptual, the technical details of the R interpreter are obviously a little more complicated.

+7


source







All Articles