Why does running `f <- function(x){x} %>% f` not throw an error?

Viewed 71

R does not complain when one runs:

library(magrittr)
f <- function(x){x} %>% f

(but running f(1) throws a C stack error).

However, isn't it equivalent to:

f <- f(function(x){x})

which throws the error f not found?

Why does the first command not throw an error?

3 Answers

function binds less strongly than the infix operator %>%. This means that your code is equivalent to

f <- function(x) ({x} %>% f)

And not to

f <- (function(x) {x}) %>% f

The latter does indeed raise the error you’re expecting.

This is equivalent to :

f <- function(x) f(x)

and results in an infinite recursive call

Ah I understand:

> body(f)
{
    x
} %>% f

In fact this is equivalent to f <- function(x){{x} %>% f}.

Related