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))
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))
You could try this:
ifelse(eval(parse(text = paste0(a, condition, b))), 'good', 'bad')
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.
Also would work:
ifelse(do.call(condition, list(a, b)), "good", "bad")
As >
is a function in R.