3

How can I evaluate an ifelse() statement using a condition stored in a character vector?

For example:

a <- 1
b <- 2
condition <- ">"

ifelse(a condition b, print("good"), print("bad))
zephryl
  • 14,633
  • 3
  • 11
  • 30
Erazijus
  • 71
  • 5

3 Answers3

5

You could try this:

ifelse(eval(parse(text = paste0(a, condition, b))), 'good', 'bad')
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
5

Here is another option with match.fun -

a <- 1
b <- 2
condition <- ">"
if(match.fun(condition)(a, b)) 'good' else 'bad'
#[1] "bad"

Since this is a scalar comparison I'm using if/else instead of vectorised ifelse. If a and b are vectors use ifelse.

Some readings about why eval(parse(...)) is bad.

I agree with @Roland's comment that we should avoid saving condition as character to avoid this problem completely. However, sometimes it is not possible to do that. I have experienced such situation especially while working with shiny applications where we want to apply such functions on the fly, in such case, I use match.fun option.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Very helpful insights here, and a small rabbit-hole to go down for reasons and alternatives. `get(condition)(a, b)` technically works as well, but `match.fun` seems much more reliable! – Andy Baxter Nov 21 '22 at 14:39
  • Thanks Ronak for the links. I wasn't aware of this issue. – Anoushiravan R Nov 21 '22 at 15:40
3

Also would work:

ifelse(do.call(condition, list(a, b)), "good", "bad")

As > is a function in R.

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22