Defining Your Own R Operators

for better readability and for its sheer awesomeness!

Haroun Shihab
Optima . Blog
1 min readDec 17, 2015

--

Say you are on your R console, writing some R code that will conquer the world! Let’s say you reached the point where you want to check the non-existence of the letter “a” in a list of characters [“a”, “b”, “c”]. So, you might think, negating the %in% operator like this:

… but conquering the world requires more readability! So how about we define our own negation operator? This is done like this:

Using our freshly minted negation operator makes for much more readable code:

The source of this tip is this tweet by LearnR.

Why stop at negation? We can extend this neat trick to build other operators as well. For example we can create a binary addition operator like this:

Now you are much more equipped for that world conquest thing!

How this post came to be? Every week at Optima, everyone on the team gets five minutes or so to share a “nugget” of data science, algorithms or related knowledge. The only rule is that it can be explained and grasped in 5 to 10 minutes. Lately we decided to share these nuggets with the world. So here we are.

--

--