Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a character type to a logical

Tags:

r

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?

like image 843
sph21 Avatar asked Jul 23 '12 14:07

sph21


1 Answers

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:

  • R: eval(parse(...)) is often suboptimal
  • Evaluate expression given as a string
  • Assigning and removing objects in a loop: eval(parse(paste(
  • R: eval(parse()) error message: cannot open file even though "text=" is specified in parse
like image 126
Andrie Avatar answered Oct 21 '22 11:10

Andrie