我一直在尝试使用 dplyr 过滤 R 中的任何缺失值,但我似乎没有做对。任何领导将不胜感激。
library(dplyr)
library(tibble)
set.seed(2021)
testdata <- tibble(
a1 = c(10, 12, NA, 10, 13),
a2 = c("Test", "Test1", "Test 2", NA, NA),
a3 = c(NA, "Test 10", "Test 2", NA, "Test 4"),
a4 = rbinom(5, 10, 0.5)
)
testdata2 <- testdata %>%
filter(across(.cols = everything(), ~any_vars(is.na(.))))
最佳答案
如果您使用 dplyr
来执行此操作,您可以使用函数 if_all
/if_any
来执行此操作。
选择至少有一个缺失值的行-
library(dplyr)
testdata %>% filter(if_any(.fns = is.na))
# a1 a2 a3 a4
# <dbl> <chr> <chr> <int>
#1 10 Test NA 5
#2 NA Test 2 Test 2 6
#3 10 NA NA 5
#4 13 NA Test 4 6
选择没有缺失值的行-
testdata %>% filter(if_all(.fns = Negate(is.na)))
# a1 a2 a3 a4
# <dbl> <chr> <chr> <int>
#1 12 Test1 Test 10 6
关于r - 过滤 R 中的任何缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70848048/