簡體   English   中英

dplyr 過濾器基於跨列和列內的條件

[英]dplyr filter based on conditions across and within column

我想驗證調查響應,包括根據列內和跨列的條件刪除帶有 NA 的行。 下面的示例數據集

col1 <- c("Yes", "Yes", "No", "No", NA)
col2 <- c("Yes", NA, "No", NA, NA)
col3 <- c("No", "Yes", "No", NA, NA)

dataset <- data.frame(col1, col2, col3)
dataset

所需的輸出涉及過濾掉 col1 中的所有行,然后僅刪除 col1 中為 Yes 且任何其他列中為 NA 的行。 所需的輸出低於`

  col1 col2 col3
1  Yes  Yes   No
2   No   No   No
3   No <NA> <NA>

` 我試過基本的過濾操作,比如

dataset %>% filter(col1 == "Yes" | !is.na(.)) 

與其他運算符,如“&、|” 但沒有運氣,我不確定如何在此處應用 across 或 filter_if 以使其工作。 我認識到這與https://stackoverflow.com/questions/43938863/dplyr-filter-with-condition-on-multiple-columns非常相似,但不同之處足以保證再次問這個問題。

我在這里錯過了什么?

您的邏輯封裝有:

dataset %>%
  filter(!(is.na(col1) | (col1 == "Yes" & (is.na(col2) | is.na(col3)))))
#>   col1 col2 col3
#> 1  Yes  Yes   No
#> 2   No   No   No
#> 3   No <NA> <NA>

我們可以用縮進和注釋重寫它,使邏輯更清晰:

dataset %>%
  filter(!(                       # Remove any of the following cases:
      is.na(col1)                       # Column 1 is missing
      |                               # OR 
      (col1 == "Yes"                    # col1 is yes               
       &                                # AND
      (is.na(col2) | is.na(col3))       # Either col2 OR col3 are missing
      )
 ))
#>   col1 col2 col3
#> 1  Yes  Yes   No
#> 2   No   No   No
#> 3   No <NA> <NA>

可以使用if_any來處理第二個過濾條件:

dataset %>% 
  filter(complete.cases(col1), 
         !(col1 == "Yes" & if_any(-col1, is.na)))

  col1 col2 col3
1  Yes  Yes   No
2   No   No   No
3   No <NA> <NA>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM