Pass an operator without backticks

Viewed 58

I have a function that I want to pass an operator to, like so:

foo <- function(a, b, op){
  op(a, b)
}

foo(1, 2, `>`)
#> [1] FALSE

Created on 2020-07-31 by the reprex package (v0.3.0)

This is exactly what I want. My question is, can I achieve the same goal without the backticks? That is, so the function call would be

foo(1, 2, >)
2 Answers

I suppose this does not fully answer your question, but you can use magrittr to avoid backsticks:

foo(a = 1, b = 2, op = is_less_than)

[1] TRUE

foo(a = 1, b = 2, op = is_greater_than)

[1] FALSE

Kind of the long way around, but if you have a strictly limited set of operators you intend to use, you could create a bunch of functions. (this is an extension of the idea in tmfmnk's answer)

myplus <-function(x,y) x + y
mygt <- function(x,y) x > y

and so on. This requires more keystrokes than simply typing

`>`

But at least it avoids having to think about backticks.

Even worse :-), create a vector of char arrays

myops = c('>','<' , '%%',[etc])  

and pass myops[k] as an argument to the function, either parsing it internally or setting up a switch construction which applies the desired operator based on the char string you supply. I don't recommend this except as an exercise in learning how R works with parsing, expressions, etc.

Related