user3212376
user3212376

Reputation: 257

Dynamically evaluate conditional expression in r

Suppose I have a data frame

x1 <- c(1, 2, 3)
x2 <- c("a", "a", "c")
x3 <- c(10, 33, 45)
x <- data.frame(x1, x2, x3)

dimensions <- c("x1", "x2")
operators <- c(">", "==")
conditions <- c(1, "a")

Ideally, the output should be equivalent to the following expression in this case

x.filtered <- which(x$x1 > 1 & x$x2 == "a")

How do I dynamically setup and evaluate the expression above using "dimensions", "operators" and "conditions" vectors?

Thanks in advance.

Upvotes: 2

Views: 289

Answers (2)

droopy
droopy

Reputation: 2818

one possibility :

expr <- paste(dimensions, operators, conditions, collapse=" & ")
expr <- gsub("(?<=(= ))(\\w+\\b)", "'\\2'", expr, perl=T)
# or
expr <- gsub("(?<=(= ))([^0-9[:punct:]]+\\b)", "'\\2'", expr, perl=T)
filter <- eval(parse(text=expr), envir=x)
# then if you really need it you can use which
which(filter) 

Upvotes: 2

user3212376
user3212376

Reputation: 257

Okay, after some fiddling around, I found the solution to my problem

text1 = paste("x[", '"', dimensions[1],'"',"]", operators[1],'"',conditions[2],'"', sep="")
eval(parse(text = text1))
which(eval(parse(text = text1)))

I can use a loop and intersect() to iterate through each and every condition. Any other improvements on this solution are most welcome.

Hope this helps!!!

Upvotes: 0

Related Questions