Why doesn't the infix function := from tidyverse need the % around it?

97 views Asked by At

If one is to create their own infix function, it needs to have the form %fun_name%. Why isn't that the case with := of tidyverse? Also, the same with the operator !!, also form tidyverse.

1

There are 1 answers

0
bcarlsen On

These operators are not functions. They are only meaningful when supplied as part of arguments to functions that use non-standard evaluation and know how to handle them. The R interpreter does not treat these operators as functions and you cannot call them directly. If you call !!something outside of a quasiquoted argument the interpreter treats it as:

!(!(something))

If you call := outside of a quasiquoted argument you get an exception.

As an aside, you can always overload base infix functions or define new S3 methods for them without needing %. The interpreter always treats these symbols as infix functions and they are not reserved. e.g:

> `+` <- function(x,y) x - y

> 1 + 2
[1] -1

`/.foo` <- function(x, y) x * y

> my_object <- structure(1, class = "foo")

> 1 / 2
[1] 0.5

> my_object / 2

[1] 2
attr(,"class")
[1] "foo"

For some reason R does allows the definition of a function := and will evaluate the resulting function as an infix function. However, this is not how rlang or data.table actually implement :=. Other symbols that begin with :, e.g. :+, or end with =, e.g. !=, are not interpreted as infix functions; I am not sure why this should be the case, as the symbol := is not used in base R. The interpreter's unique ability to evaluate it as an infix function is unexpected, at least to me.


> `:=` <- function(x,y) x - y

> 5 := 2

[1] 3