如何使用 dplyr across 过滤多列中的 NA

etr*_*dge 7 r dplyr

我正在尝试过滤掉多列中具有 NA 值的行。仅当所有感兴趣的列均为 NA 时才应删除行。

场景与这个问题相同(但我没有足够的声誉来发表评论):filtering dataframe based on NA on multiple columns

解决方案之一是使用:

library(dplyr)
df_non_na <- df %>% filter_at(vars(type,company),all_vars(!is.na(.)))
Run Code Online (Sandbox Code Playgroud)

由于“filter_at”在 dplyr 中被贬值,我如何使用“filter”和“across”来实现类似的结果?

akr*_*run 11

我们可以使用across循环“type”、“company”列并返回指定列中没有任何 NA 的行

library(dplyr)
df %>%
     filter(across(c(type, company), ~ !is.na(.)))
#     id  type company
#1  3 North    Alex
#2 NA North     BDA
Run Code Online (Sandbox Code Playgroud)

对于filter,有两个与all_vars/any_vars使用类似的选项filter_at/filter_all

df %>%
  filter(if_any(c(company, type), ~ !is.na(.)))
#  id  type company
#1  2  <NA>     ADM
#2  3 North    Alex
#3  4 South    <NA>
#4 NA North     BDA
#5  6  <NA>      CA
Run Code Online (Sandbox Code Playgroud)

或者使用if_all

    df %>%
      filter(!if_all(c(company, type), is.na))
   id  type company
1  2  <NA>     ADM
2  3 North    Alex
3  4 South    <NA>
4 NA North     BDA
5  6  <NA>      CA
Run Code Online (Sandbox Code Playgroud)

数据

df <- structure(list(id = c(1L, 2L, 3L, 4L, NA, 6L), type = c(NA, NA, 
"North", "South", "North", NA), company = c(NA, "ADM", "Alex", 
NA, "BDA", "CA")), class = "data.frame", row.names = c(NA, -6L
))
Run Code Online (Sandbox Code Playgroud)