0

How (and can) I use different operators on command in if and else function?

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){operator.is <- <}else{operator.is <- >}

sub <- subset(x, x operator.is 2)

#expected results
sub
[1] 3 4 5 6 7 8

I want to store the operator in "operator.is", based on the if statement. Yet, I do not seem to be able to store an operator and use it in the subset function. Later in want to use this operator to subset. Without this I will need to copy and past the whole code just to use the other operator. Is there any elegant and simple way to solve this?

Thanks in advance

A4-paper
  • 64
  • 8

2 Answers2

0

operators can be assigned with the % sign:

`%op%` = `>`

vector <- c(1:10)

vector2 <- subset(vector, vector %op% 5)

In your case:

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){`%operator.is%` <- `<`}else{`%operator.is%` <- `>`}

sub <- subset(x, x %operator.is% 2)
Sven
  • 1,165
  • 1
  • 4
  • 14
0
x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){`%my_op%` <- `<`}else{`%my_op%` <- `>`}

sub <- subset(x, x %my_op% 2)
sub
##[1] 4 5 6 7 8

"Things to remember while defining your own infix operators are that they must start and end with %. Surround it with back tick (`) in the function definition and escape any special symbols."

from https://www.datamentor.io/r-programming/infix-operator/

better to follow the lead of @Oliver and just

x <- as.numeric(c(1,1,4,5,6,7,8))

if(mean(x) < 3){operator.is <- `<`}else{operator.is <- `>`}

sub <- subset(x, operator.is(x,2))
sub
##[1] 4 5 6 7 8
Bruce Schardt
  • 210
  • 1
  • 7