Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有多列条件的dplyr过滤器_R_Dplyr - Fatal编程技术网

具有多列条件的dplyr过滤器

具有多列条件的dplyr过滤器,r,dplyr,R,Dplyr,这是一个虚拟数据: father<- c(1, 1, 1, 1, 1) mother<- c(1, 1, 1, NA, NA) children <- c(NA, NA, 2, 5, 2) cousins <- c(NA, 5, 1, 1, 4) dataset <- data.frame(father, mother, children, cousins) dataset father mother children cousins 1

这是一个虚拟数据:

father<- c(1, 1, 1, 1, 1)
mother<- c(1, 1, 1, NA, NA) 
children <- c(NA, NA, 2, 5, 2) 
cousins   <- c(NA, 5, 1, 1, 4) 


dataset <- data.frame(father, mother, children, cousins)  
dataset


father  mother  children cousins
1      1       NA      NA
1      1       NA       5
1      1        2       1
1     NA        5       1
1     NA        2       4
我可以用:

test <- dataset %>% 
filter(father==1 & mother==1) %>%
filter (is.na(children)) %>%
filter (is.na(cousins))
test  

如何使用dplyr表示使用na过滤所有列(父==1和母==1除外)

这里有一个基本R方法,使用两个
Reduce
函数和
[
到子集

keepers <- Reduce(function(x, y) x == 1 & y == 1, dataset[, 1:2]) &
           Reduce(function(x, y) is.na(x) & is.na(y), dataset[, 3:4])
keepers
[1]  TRUE FALSE FALSE FALSE FALSE

A
dplyr
解决方案:

test <- dataset %>% 
  filter(father==1 & mother==1 & rowSums(is.na(.[,3:4]))==2)

您也可以在base R中应用此逻辑:

dataset[dataset$father==1 & dataset$mother==1 & rowSums(is.na(dataset[,3:4]))==2,]

一个可能的
dplyr
(0.5.0.9004答案似乎都不是一个合适的解决方案。我认为目的不是列出所有变量和值来过滤数据

实现这一点的一个简单方法是合并。如果您在df_filter中具备所有条件,则可以执行以下操作:

df_results = df_filter %>% left_join(df_all)
dplyr>=1.0.0 如果您使用的是dplyr version>=1.0.0,那么您真的应该使用
If_any
If_all
,它专门将谓词函数的结果组合到一个逻辑向量中,使其在
过滤器中非常有用。语法与跨
相同,但添加这些动词是为了帮助满足这一需要:。

输出

  father mother children cousins
1      1      1       NA      NA

非常感谢。我正在寻找dplyrIMO,您应该将数据转换为长格式()可能的重复项不清楚“df_过滤器中的所有条件”意味着。我怀疑dplyr代码中的所有条件,但您的代码示例表明并非如此。请澄清这意味着所有单元格都满足条件。如问题“我想筛选此行:”中给出的示例。
> test
  father mother children cousins
1      1      1       NA      NA
dataset[dataset$father==1 & dataset$mother==1 & rowSums(is.na(dataset[,3:4]))==2,]
# > packageVersion('dplyr')
# [1] ‘0.5.0.9004’

dataset %>%
    filter(!is.na(father), !is.na(mother)) %>%
    filter_at(vars(-father, -mother), all_vars(is.na(.)))
dataset %>%
    filter(across(c(father, mother), ~ !is.na(.x))) %>%
    filter(across(c(-father, -mother), is.na))
df_results = df_filter %>% left_join(df_all)
library(dplyr)

dataset %>% 
  filter(if_all(-c(father, mother), ~ is.na(.)) & if_all(c(father, mother), ~ !is.na(.)))
  father mother children cousins
1      1      1       NA      NA