在r中,过滤所有满足多个条件的组

问题描述 投票:0回答:1

这是我的 df 的一个例子:

df <- data.frame(species= c("dog", "dog", "dog", "cat", "cat", "fish", "fish"), percentage = c(12, 13, 19,  20, 12,  10, 50))

我想过滤 df 以仅包含百分比为 <13 AND >13 的物种。在那 df 中,只有狗。

我试过这个:

df %>% group_by(species) %>% filter(any(percentage < 13 & percentage >13))

但是我得到一个空的 df... 谢谢!

r sorting dplyr filter grouping
1个回答
0
投票

我只是假设你的示例数据是错误的,因为正如 Stefan 在评论中指出的那样,“你的所有三个物种的 obs 百分比都为 < 13 and percentage > 13。”。

如果我们更改示例数据,我们可以过滤掉狗,这是目前唯一观测值大于和小于 13 的物种。

我们可以使用

any
(或者对于其他条件使用
all
)通过分组过滤器来完成此操作。

library(tidyverse)

df <- data.frame(species= c("dog", "dog", "dog", "cat", "cat", "fish", "fish"), percentage = c(12, 13, 19,  20, 16,  14, 50))

df
#>   species percentage
#> 1     dog         12
#> 2     dog         13
#> 3     dog         19
#> 4     cat         20
#> 5     cat         16
#> 6    fish         14
#> 7    fish         50

df %>% 
  group_by(species) %>% 
  filter(any(percentage > 13),
         any(percentage < 13))

#> # A tibble: 3 × 2
#> # Groups:   species [1]
#>   species percentage
#>   <chr>        <dbl>
#> 1 dog             12
#> 2 dog             13
#> 3 dog             19

创建于 2023-12-17,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.