【问题标题】:R / dplyr : How to use filter functions in conjunction with the pipelining %>% operator?R / dplyr:如何将过滤器功能与流水线 %>% 运算符结合使用?
【发布时间】:2014-07-25 15:27:51
【问题描述】:

我确信这样做有一个习惯用法,但我究竟如何使用 dplyr 将布尔掩码或行选择通过管道传输到过滤器操作。

例如,这里我想选出 foo 的 id 重复的行:

foo$id %>% duplicated %>% filter(foo ??)

我可以使用匿名函数来做到这一点,但一定有更好的方法:

foo$id %>% duplicated %>% function(x) foo[x,]

【问题讨论】:

  • 你能用foo %>% filter(duplicated(id))代替吗?
  • 您能否提供 foo 以使其成为最小的工作代码,否则这是关闭问题的理由?

标签: r dplyr


【解决方案1】:

问题在于,当 dplyr 确实要与类似表格的对象一起使用时,您正试图将向量发送到管道中,因此您应该发送整个 data.frame(假设这就是 foo 的内容。例如

library(dplyr)
foo <- data.frame(id=sample(1:5, 25, replace=T), val=runif(25))
foo %>% filter(!duplicated(id))

如果你真的只想要ID,那么添加

foo %>% filter(!duplicated(id)) %>% select(id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2014-12-31
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多