首页 > 解决方案 > 在 R 中选择性地过滤多个变量

问题描述

我正在使用 Tidyverse

animals <- c("Bat", "Monkey", "Tiger", "Frog", "Bald Eagle")
Type <- c("mammal","mammal","mammal", "Amphibian", "Bird")
Quantity <- c(8, 5, 1, 5, 1)
Bananas <-  c(0,1,0,0,0)
Apples <- c(0,1,0,0,0)
Crickets <- c(1,0,0,1,0)
DF <- data.frame(animals, Type, Quantity,Bananas, Apples, Crickets)

#DF looks like this 
     animals      Type Quantity Bananas Apples Crickets
1       Bat     mammal        8       1      1        0
2     Monkey    mammal        5       1      1        0
3      Tiger    mammal        1       0      0        0
4       Frog    Amphibian     5       0      0        1
5 Bald Eagle    Bird          1       0      0        0

我正在寻找一种简单的方法来过滤显示的结果:

  1. 只有行是哺乳动物和
  2. 只有 Bananas、OR Apples、OR Crickets 等于 1 的行
#desired results
  animals   Type Quantity Bananas Apples Crickets
1    Bat  mammal        8       0      0        1
2  Monkey mammal        5       1      1        0

我一直在尝试使用 filter_all(any_vars) 并做条件,但在它起作用的情况下,我仍然让 Tiger 出现在最终列表中,因为它在数量变量中有“1”。

我需要一种干净的方法来进行此过滤,我不想丢失任何列,在真实数据集中需要保留 50 列其他信息。

谢谢!

标签: rfilter

解决方案


过滤两次应该可以工作,使用 | 第二次通话的接线员。

DF %>%
    filter(Type == "mammal", Bananas == 1 | Apples == 1 | Crickets == 1)

更明确地说,在两个单独的过滤器调用中:

DF %>%
    filter(Type == "mammal") %>%
    filter(Bananas == 1 | Apples == 1 | Crickets == 1)

推荐阅读