0

I would like to execute a logical operation using a character string (yes I want to do it this way)

a = data.frame(x=c(1,2,3,4),y=c(11,12,13,14))
logical_text = "a$x!=2 & a$y!=14"

a
> a
  x  y
1 1 11
2 2 12
3 3 13
4 4 14

I am hoping to use the string as follows

  a[logical_text,]
> a[logical_text,]
    x  y
NA NA NA

In order to get the same result as:

a[a$x!=2 & a$y!=14,]
> a[a$x!=2 & a$y!=14,]
  x  y
1 1 11
3 3 13

1 Answer 1

6

It's not necessarily a good idea to do things this way. But if you really must you can use eval(parse(text = your_command_as_a_string_here)) to evaluate a string as if it were code

a = data.frame(x=c(1,2,3,4),y=c(11,12,13,14))
logical_text = "a$x!=2 & a$y!=14"

# Evaluate logical_text into a temporary logical variable
logical_output <- eval(parse(text = logical_text))
a[logical_output,]
#  x  y
#1 1 11
#3 3 13

# Same thing but without storing as a temporary variable.
a[eval(parse(text=logical_text)), ]
#  x  y
#1 1 11
#3 3 13
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.