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

  • So you want to subset `x` according to `mean(x) < 3` ? Where does `3` come from in your expected output? Also, no need for `as.numeric` in your first line. – markus May 14 '19 at 07:51
  • Any operator is just a function. `operator.is <- \`<\`; operator.is(3,4)` – Oliver May 14 '19 at 07:51
  • You might [use `switch`](https://stackoverflow.com/questions/10393508/how-to-use-the-switch-statement-in-r-functions) – markus May 14 '19 at 08:07
  • The 3 was just a random chosen number for this example. –  May 14 '19 at 11:45

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,203
  • 1
  • 5
  • 14
  • Yes, perfect, thank you. Easy and simple. Found the answer somewhere else as well. –  May 14 '19 at 11:45
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