user7273584
user7273584

Reputation: 35

How to use an element in a list as a condition in ifelse

I have a list with multiple conditional statements as each element. I want to use each element in the list as a conditional statement, specifically in an ifelse statement. I've tried different combinations of noquote, paste, etc. and still only receive NA as a returned value. Here is some test data:

#Set these equal to some number to test the ifelse statement
B11 <- 0.1
B15 <- 0.03
#Create a list of conditions
l <- list("B11 >= -0.012 & B15 >=  0.030")
#Somehow evaluate the condition within an ifelse statement
ifelse(l[[1]], "yes", "no")
#This should return "yes" but always returns NA

Upvotes: 0

Views: 1327

Answers (2)

Jonas
Jonas

Reputation: 1810

If you have the condition given as a string, you have to tell R that the string is not simply a string, but rather a command. To tell R that the string is a command, use eval(parse(text=...)).

In your case

ifelse(eval(parse(text=l[[1]])), "yes", "no")

But you have to make sure that there is no malicious command given in the string when evaluating it, like eval(parse(text="q('no')")). The function q quits your current Rsession and the argument no stands for not saving the current workspace.

Upvotes: 1

Rutangaba
Rutangaba

Reputation: 439

You created the list using your condition like string, not like a condition. To work what you want, you have to remove double quote, like this:

l <- list(B11 >= -0.012 & B15 >=  0.030)

ifelse(l[[1]], "yes", "no")

Output:

[1] "yes

Hope was helpful.

Upvotes: 2

Related Questions