mmann1123
mmann1123

Reputation: 5295

Subset a data.frame using logical character strings

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

Upvotes: 0

Views: 721

Answers (1)

Dason
Dason

Reputation: 61903

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

Upvotes: 6

Related Questions