r - 在 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
我正在寻找一种简单的方法来过滤显示的结果:
- 只有行是哺乳动物和
- 只有 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 列其他信息。
谢谢!
解决方案
过滤两次应该可以工作,使用 | 第二次通话的接线员。
DF %>%
filter(Type == "mammal", Bananas == 1 | Apples == 1 | Crickets == 1)
更明确地说,在两个单独的过滤器调用中:
DF %>%
filter(Type == "mammal") %>%
filter(Bananas == 1 | Apples == 1 | Crickets == 1)
推荐阅读
- swift - 将结构数组中的 UIColor 保存到 UserDefaults
- html - 页面没有响应 Div 标签
- angular-material - Angular Material:为什么 mat-form 没有将 mat-hint 包裹在里面?
- python - 递归函数下只在if语句中返回
- vba - 从字符串中间删除零
- powerbi - 如何在 PowerBI 的矩阵视觉中将度量显示为子列
- python - 如何使用python将数据导出到csv
- c++ - 如何生成类似 OR 的语句编译时间?C++
- python - Django Admin - 通过模型过滤 ManyToManyField
- mysql - 如何将表内的属性引用到同一表内新行内的值