I'm trying to create some code that is very user friendly to someone not that familiar with R. The code is designed so that the logical criteria can easily be manipulated, based on what the user is looking for. So instead of forcing the user to work within the if statements, I would like to just create a character variable containing the logical statement at the top of the code (i.e. x <- "a > 2"
).
Then I would like to evaluate an if statement using that character variable containing a logical operator. Here is the basic idea:
a <- 3
x <- "a > 2"
if(x)TRUE
This obviously returns an error that the argument is not interpretable as logical, because it sees x as the character string "a > 2."
I know I could simply do:
a <- 3
x <- as.logical(a > 2)
if(x)TRUE
However, in the case of what I'm working on, it would be preferable to initially store these logical statements as characters. And as.logical() does not seem to be able to convert characters (i.e. as.logical("a > 2")
) does not work.
My question: Is there some function I can put x through that allows R to view it not as a character, but rather as a logical statement? In other words, how can I just strip away the quotation marks so that the logical statement can work inside an if statement?
You can use eval(parse(...))
.
a <- 3
x <- "a > 2"
eval(parse(text=x))
[1] TRUE
x2 <- "a==3"
eval(parse(text=x))
[1] TRUE
Here be dragons.
See, for example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With