user3375672
user3375672

Reputation: 3768

How to supply (logical) operators as arguments to function

Is it possible to supply logical (or arithmetic) operators as arguments to R functions. Check this SO question that share the theme.

f1 <- function(a, b) a>b

Then

> f1(1,2)
[1] FALSE

How can I implement an operator that allows me to for instance change the function test, e.g.

f2 <- function(a, b, operator = c('<', '>', '==')) { ... }

Then I would like

> f2(1, 2, '<')
[1] TRUE

Upvotes: 4

Views: 714

Answers (3)

talat
talat

Reputation: 70266

Here's another option:

foo <- function(a, b, operator) {
   f <- match.fun(match.arg(operator, choices = c('<', '>', '=='))) 
   f(a,b) 
}

foo(1,2, ">")
#[1] FALSE
foo(1,2, "==")
#[1] FALSE
foo(1,2, "+")
# Show Traceback
# 
# Rerun with Debug
# Error in match.arg(operator, choices = c("<", ">", "==")) : 
#  'arg' should be one of “<”, “>”, “==” 

Using match.arg allows you to restrict it to certain functions. match.fun then gets the actual function.

In case you don't need the restriction to certain inputs, you can skip the match.arg and just use match.fun.

Upvotes: 3

Sotos
Sotos

Reputation: 51592

One way to do this is to use eval(parse(...)) methodology, i.e.

f1 <- function(a, b, op){
  eval(parse(text = paste0(a, op, b)))
}

f1(1, 2, '<')
#[1] TRUE
f1(3, 3, '==')
#[1] TRUE
f1(3, 4, '==')
#[1] FALSE

Upvotes: 2

Roland
Roland

Reputation: 132706

In R, all operators are functions. So, you only need to get the operator function and call it.

f2 <- function(a, b, operator) getFunction(operator)(a, b)
f2(1, 2, '<')
#[1] TRUE

Upvotes: 9

Related Questions