14

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?

sph21
  • 300
  • 1
  • 3
  • 11
  • "I'm trying to create some code that is very user friendly to someone not that familiar with R." — there are some who might say that is impossible _signed someone who loves R despite its wretched syntax_ – msw Jul 23 '12 at 14:30
  • How far do you want to go to isolate the user from R? If your user is not comfortable with things like " '&' means AND" then it's not going to matter much whether the input is a string or a statement. Are you trying to make it easy for the user to edit a function, or to provide inputs to a function? Basically, I think anyone who can understand how to build a logical test such as `if y>2*z .OR. (y< x .AND. y < z/3) ` can easily learn to do so in R syntax. – Carl Witthoft Jul 23 '12 at 16:56
  • My goal is not so much to get away from R syntax. I have many if statements throughout the code that rely on a few simple criteria inputs at the beginning. I was just trying to make it quick and easy for the user to change the initial criteria inputs at his discretion without having to search through the code. Keeping everything as character inputs at the beginning allows me to separate each aspect of the logical statement. The user first chooses which parameters to look at, which logical operator to apply to each parameter (==, >, <...), and to what numerical value. Then I can concatenate. – sph21 Jul 23 '12 at 17:44

1 Answers1

12

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:

Community
  • 1
  • 1
Andrie
  • 176,377
  • 47
  • 447
  • 496