Mehdi Zare
Mehdi Zare

Reputation: 1381

Parsing a character string condition in R

I have a character string and wants R to treat it as a logical condition to be used in an if loop.

condition <- "df$a > 2"

How can I force R to treat condition as a logical so that this if statement works?

if(condition){
  print(df$a)
}

Upvotes: 0

Views: 1940

Answers (3)

Dave Rosenman
Dave Rosenman

Reputation: 1467

You could use parse(text = condition) to parse the string to an expression. Then use eval to evaluate the expression:

a <- 4
condition <- "a > 2"

if (eval(parse(text = condition))) {
  print(a)
}

Upvotes: 3

Mehdi Zare
Mehdi Zare

Reputation: 1381

It can be simply achieved with a call to eval and parse functions from base R

if(eval(parse(text = condition)){
  print(df$a)
}

Upvotes: 0

jdobres
jdobres

Reputation: 11957

You can do this with parse and eval. For example:

condition <- "2 + 2"

if (eval(parse(text = condition)) > 1) {
  print('true')
}

[1] "true"

Upvotes: 4

Related Questions