How to Define the Operator %% in R
Overview
In R, it is possible to define a function as a binary operator right away. The remainder operation %%
, the quotient operation %/%
, dot product %*%
, %o%
or inclusion %in%
, and the pipe operator %>%
that are already defined in R also belong to these binary operators.
Code
For instance, in a language like Python, adding strings together concatenates them, which is very convenient, but R is somewhat inconvenient in comparison. Considering binary operators as a solution to this could be helpful.
Handling data, as well as dealing with strings becomes frequent, and it’s rather inconvenient to concatenate strings functionally every time. Therefore, creating an operator that can be used even briefly like above is convenient.
"%++%" <- function(x,y) {paste(x,y)}
example <- "Oh" %++% "My" %++% "Girl"
print(example)