0

This is probably an easy one.

In R, can I replace an if condition character (such as >) with a character and execute the if statement with it?

For example, if the if statement is:

ifelse(1 < 2, "T", "F")

But I'm getting the > condition character through a variable:

cc <- ">"

How would I write:

ifelse(1 < 2, "T", "F")

replacing < with cc?

dan
  • 6,048
  • 10
  • 57
  • 125
  • Very close to https://stackoverflow.com/questions/55807468/evaluate-different-logical-conditions-from-string-for-each-row/ since all answers there can be applied here. – Ronak Shah Apr 26 '19 at 01:32

1 Answers1

2

As it is a relational operator in R, we can use match.fun

cc <- "<"
ifelse(match.fun(cc)(1, 2), "T", "F")
#[1] "T"

This ifelse can be simplified but I assume this is just an example and you want to do something more complicated.


You can also get the required output using eval(parse.. but I would not recommend it

ifelse(eval(parse(text = paste(1, cc, 2))), "T", "F")
#[1] "T"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213