【问题标题】:Using "any" operator in dplyr filter在 dplyr 过滤器中使用“任何”运算符
【发布时间】:2018-10-31 10:05:00
【问题描述】:

我正在尝试在 dplyr 包的“过滤器”中使用“任何”运算符 像这样:

 library(tidyverse)

 iris %>%
   as_tibble() %>%
   filter( any(Species == "setosa",
               Species == "versicolor") )

# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
 1          5.1         3.5          1.4         0.2 setosa 
 2          4.9         3            1.4         0.2 setosa 
 3          4.7         3.2          1.3         0.2 setosa 
 4          4.6         3.1          1.5         0.2 setosa 
 5          5           3.6          1.4         0.2 setosa 
 6          5.4         3.9          1.7         0.4 setosa 
 7          4.6         3.4          1.4         0.3 setosa 
 8          5           3.4          1.5         0.2 setosa 
 9          4.4         2.9          1.4         0.2 setosa 
10          4.9         3.1          1.5         0.1 setosa 
# ... with 140 more rows

由于某种原因,过滤器被忽略,因为 iris 包含 150 行。

但是当“|”使用运算符返回正确的行数:

 library(tidyverse)

 iris %>%
   as_tibble() %>%
   filter( Species == "setosa" | 
             Species == "versicolor" )

# A tibble: 100 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
 1          5.1         3.5          1.4         0.2 setosa 
 2          4.9         3            1.4         0.2 setosa 
 3          4.7         3.2          1.3         0.2 setosa 
 4          4.6         3.1          1.5         0.2 setosa 
 5          5           3.6          1.4         0.2 setosa 
 6          5.4         3.9          1.7         0.4 setosa 
 7          4.6         3.4          1.4         0.3 setosa 
 8          5           3.4          1.5         0.2 setosa 
 9          4.4         2.9          1.4         0.2 setosa 
10          4.9         3.1          1.5         0.1 setosa 
# ... with 90 more rows

是否可以使用带有 dplyr 过滤器的“any”运算符使代码工作?

拉斐尔

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    any 在您的代码中的作用是什么?我想你只是想要

    … %>% filter(Species == "setosa" | Species == "versicolor")
    

    或者

    … %>% filter(Species %in% c("setosa", "versicolor"))
    

    在任何一种情况下,filter 中的表达式都会返回一个与数据框内的行相对应的 向量。相比之下,any 返回一个 单个 值,TRUE 或 FALSE 因此它要么过滤 所有 行,要么不过滤。

    【讨论】:

    • 好的。感谢您的解释,我现在明白为什么“任何”不起作用。确实我想实现“... %>% filter(Species == "setosa" | Species == "versicolor")" 但使用 any 因为它的垂直缩进更好。从我的帖子中的两段代码中可以看出..
    猜你喜欢
    • 2018-07-03
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多