I'm trying to use dplyr
to filter
my data based on a test condition, but this test condition can change depending on other variables.
Using the built in sample dataset cars
:
data(cars)
I'd like to do something like this:
if (foo == 0) {
test <- speed > 15
} else {
test <- dist < 50
}
filter(cars, test)
This doesn't work. I can get it to work if I alter it to something like this:
if (foo == 0) {
test <- 'cars$speed > 15'
} else {
test <- 'cars$dist < 50'
}
filter(cars, eval(parse(text = test)))
But
- Having to type out
cars$speed
andcars$dist
seems to defeat the purpose of using thefilter
function. - According to this SO answer, using the
eval(parse(text = ...))
construction is not recommended.
Is there a better way of achieving this?