我有一个样本数据集,如下所示:
father<- c(1, 1, 1, 0, 0)
mother<- c(1, 1, 1, 0, 0)
children <- c(0, 0, 2, 5, 2)
cousins <- c(0, 5, 1, 1, 4)
dataset <- data.frame(father, mother, children, cousins)
dataset
father mother children cousins
1 1 0 0
1 1 0 5
1 1 2 1
0 0 5 1
0 0 2 4
我想应用一个基于条件的过滤器,这样我就可以得到所有标记为"1"的父亲,母亲将为0或孩子将为0或表兄弟姐妹将为0。此外,我还希望这个过滤器能够选择所有带有0的父亲和带有0的母亲以及带有0的孩子和带有0的表亲。关于如何为我的数据集创建这样一个过滤器,有什么想法吗?
谢谢!
这是你要找的吗:
library(dplyr)
father<- c(1, 1, 1, 0, 0)
mother<- c(1, 1, 1, 0, 0)
children <- c(0, 0, 2, 5, 2)
cousins <- c(0, 5, 1, 1, 4)
dataset <- data.frame(father, mother, children, cousins)
dataset %>%
filter(father == 1 & (mother == 0 | children == 0 | cousins == 0))
#> father mother children cousins
#> 1 1 1 0 0
#> 2 1 1 0 5
dataset %>%
filter(father == 0 & mother == 0 & children == 0 & cousins == 0)
#> [1] father mother children cousins
#> <0 rows> (or 0-length row.names)
由reprex包(v2.0.1)创建于2022-06-04
使用if_any
和if_all
对@Dave的回答进行修改:
library(tidyverse)
father<- c(1, 1, 1, 0, 0)
mother<- c(1, 1, 1, 0, 0)
children <- c(0, 0, 2, 5, 2)
cousins <- c(0, 5, 1, 1, 4)
dataset <- data.frame(father, mother, children, cousins)
dataset |>
filter(father == 1, if_any(-father, ~ . == 0))
#> father mother children cousins
#> 1 1 1 0 0
#> 2 1 1 0 5
dataset |>
filter(if_all(, ~ . == 0))
#> [1] father mother children cousins
#> <0 rows> (or 0-length row.names)
由reprex包(v2.0.1)创建于2022-06-04