【发布时间】:2017-01-25 18:12:35
【问题描述】:
我正在尝试根据测试条件使用dplyr 到filter 我的数据,但此测试条件可能会根据其他变量而改变。
使用内置的示例数据集cars:
data(cars)
我想做这样的事情:
if (foo == 0) {
test <- speed > 15
} else {
test <- dist < 50
}
filter(cars, test)
这不起作用。如果我把它改成这样,我可以让它工作:
if (foo == 0) {
test <- 'cars$speed > 15'
} else {
test <- 'cars$dist < 50'
}
filter(cars, eval(parse(text = test)))
但是
- 必须输入
cars$speed和cars$dist似乎违背了使用filter函数的目的。 - 根据this SO answer,不建议使用
eval(parse(text = ...))构造。
有没有更好的方法来实现这一点?
【问题讨论】: