Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 595
user3375672 Avatar asked Oct 23 '25 03:10

user3375672


1 Answers

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
like image 93
Roland Avatar answered Oct 24 '25 18:10

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!