【问题标题】:Use string as filter in dplyr?在 dplyr 中使用字符串作为过滤器?
【发布时间】:2014-12-18 19:29:37
【问题描述】:

有没有办法在 dplyr 中使用字符串变量作为过滤器参数?例如:

filter(iris,Sepal.Length > 6)

将被替换为

string <- 'Sepal.Length > 6'
filter(iris,string)

基本上,我正在寻找整个过滤器字符串作为变量,因为我正在务实地创建过滤器字符串。感谢您的帮助。

【问题讨论】:

  • 您可能会考虑更改接受的答案,因为当前的答案已被弃用。

标签: r dplyr


【解决方案1】:

如果要使用字符串参数进行过滤,则需要使用 filter_() 而不是 filter()

string <- 'Sepal.Length > 6'
filter_(iris, string)

另外请注意,建议在编程时使用*_() 函数。

【讨论】:

  • 这个新的 tidyeval 版本现在会是什么?
  • 现在已弃用 :(
  • @ashleych 我在下面发布了一个最新的答案。
【解决方案2】:

这是我发现在新的 tidyval 中有效的唯一方法:

> s = "A<3"
> data.frame(A=1:10, B=1:10) %>% filter(eval(str2expression(s)))
  A B
1 1 1
2 2 2

不过,我还没弄明白how to do this with multiple conditions

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多