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?

1

1 Answer 1

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" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.