使用dplyr删除所有变量都为NA的行

hej*_*seb 23 r dplyr tidyverse

我在看似简单的任务时遇到了一些问题:删除所有变量都NA使用dplyr的所有行.我知道可以使用基本R(删除R矩阵中的所有数据为NA删除R中数据文件的空行)来完成,但我很想知道是否有一种简单的方法可以使用dplyr .

例:

library(tidyverse)
dat <- tibble(a = c(1, 2, NA), b = c(1, NA, NA), c = c(2, NA, NA))
filter(dat, !is.na(a) | !is.na(b) | !is.na(c))
Run Code Online (Sandbox Code Playgroud)

filter上面的调用做了我想要的但是在我面临的情况下它是不可行的(因为有大量的变量).我想可以通过使用filter_并首先使用(长)逻辑语句创建一个字符串来实现它,但似乎应该有一个更简单的方法.

另一种方法是使用rowwise()do():

na <- dat %>% 
  rowwise() %>% 
  do(tibble(na = !all(is.na(.)))) %>% 
  .$na
filter(dat, na)
Run Code Online (Sandbox Code Playgroud)

但这看起来并不太好,虽然它完成了工作.其他想法?

Mar*_*usN 32

由于dplyr 0.7.0新,因此存在范围过滤动词.使用filter_any,您可以轻松过滤至少包含一个非缺失列的行:

dat %>% filter_all(any_vars(!is.na(.)))
Run Code Online (Sandbox Code Playgroud)

使用@hejseb基准测试算法,似乎该解决方案与f4一样有效.

  • 我认为这是删除所有na行的最直观的解决方案。另外,值得一提的是当您要检测全无行时,必须使用all_vars()而不是any_vars(),如`dat%&gt;%filter_all(all_vars(is.na(。)) )` (2认同)

mha*_*nga 14

我建议在这里使用美妙的看门人包。Janitor 非常人性化:

janitor::remove_empty(dat, which = "rows")
Run Code Online (Sandbox Code Playgroud)


hej*_*seb 9

标杆

@DavidArenburg提出了许多替代方案.这是一个简单的基准测试.

library(tidyverse)
library(microbenchmark)

n <- 100
dat <- tibble(a = rep(c(1, 2, NA), n), b = rep(c(1, 1, NA), n))

f1 <- function(dat) {
  na <- dat %>% 
    rowwise() %>% 
    do(tibble(na = !all(is.na(.)))) %>% 
    .$na
  filter(dat, na)
}

f2 <- function(dat) {
  dat %>% filter(rowSums(is.na(.)) != ncol(.))
}

f3 <- function(dat) {
  dat %>% filter(rowMeans(is.na(.)) < 1)
}

f4 <- function(dat) {
  dat %>% filter(Reduce(`+`, lapply(., is.na)) != ncol(.))
}

f5 <- function(dat) {
  dat %>% mutate(indx = row_number()) %>% gather(var, val, -indx) %>% group_by(indx) %>% filter(sum(is.na(val)) != n()) %>% spread(var, val) 
}

# f1 is too slow to be included!
microbenchmark(f2 = f2(dat), f3 = f3(dat), f4 = f4(dat), f5 = f5(dat))
Run Code Online (Sandbox Code Playgroud)

使用Reduce并且lapply似乎是最快的:

> microbenchmark(f2 = f2(dat), f3 = f3(dat), f4 = f4(dat), f5 = f5(dat))
Unit: microseconds
 expr        min          lq       mean      median         uq        max neval
   f2    909.495    986.4680   2948.913   1154.4510   1434.725 131159.384   100
   f3    946.321   1036.2745   1908.857   1221.1615   1805.405   7604.069   100
   f4    706.647    809.2785   1318.694    960.0555   1089.099  13819.295   100
   f5 640392.269 664101.2895 692349.519 679580.6435 709054.821 901386.187   100
Run Code Online (Sandbox Code Playgroud)

使用更大的数据集107,880 x 40:

dat <- diamonds
# Let every third row be NA
dat[seq(1, nrow(diamonds), 3), ]  <- NA
# Add some extra NA to first column so na.omit() wouldn't work
dat[seq(2, nrow(diamonds), 3), 1] <- NA
# Increase size
dat <- dat %>% 
  bind_rows(., .) %>%
  bind_cols(., .) %>%
  bind_cols(., .)
# Make names unique
names(dat) <- 1:ncol(dat)
microbenchmark(f2 = f2(dat), f3 = f3(dat), f4 = f4(dat))
Run Code Online (Sandbox Code Playgroud)

f5太慢了所以它也被排除在外.f4似乎做得比以前好多了.

> microbenchmark(f2 = f2(dat), f3 = f3(dat), f4 = f4(dat))
Unit: milliseconds
 expr      min       lq      mean    median       uq      max neval
   f2 34.60212 42.09918 114.65140 143.56056 148.8913 181.4218   100
   f3 35.50890 44.94387 119.73744 144.75561 148.8678 254.5315   100
   f4 27.68628 31.80557  73.63191  35.36144 137.2445 152.4686   100
Run Code Online (Sandbox Code Playgroud)


jig*_*jer 7

从 dyplr 1.0 开始,colwise 小插图给出了一个类似的例子:

filter(across(everything(), ~ !is.na(.x))) #Remove rows with *any* NA
Run Code Online (Sandbox Code Playgroud)

我们可以看到它filter使用与多个表达式相同的隐式“& 逻辑” 。所以下面的小调整选择所有 NA 行:

filter(across(everything(), ~ is.na(.x))) #Remove rows with *any* non-NA
Run Code Online (Sandbox Code Playgroud)

但问题要求逆集:删除全部为NA 的行。

  1. 我们可以setdiff使用前面的做一个简单的,或者
  2. 我们可以使用across返回逻辑小标题并filter有效地按行all()(即&)执行的事实。

例如:

rowAny = function(x) apply(x, 1, any)
anyVar = function(fcn) rowAny(across(everything(), fcn)) #make it readable
df %<>% filter(anyVar(~ !is.na(.x))) #Remove rows with *all* NA
Run Code Online (Sandbox Code Playgroud)

或者:

filterout = function(df, ...) setdiff(df, filter(df, ...))
df %<>% filterout(across(everything(), is.na)) #Remove rows with *all* NA
Run Code Online (Sandbox Code Playgroud)

或者甚至结合上面2个更直接的表达第一个例子:

df %<>% filterout(anyVar(~ is.na(.x))) #Remove rows with *any* NA
Run Code Online (Sandbox Code Playgroud)

在我看来,tidyversefilter函数将受益于描述“聚合逻辑”的参数。它可以默认为“all”并保留行为,或者允许“any”,因此我们不需要编写anyVar类似帮助函数。


ale*_*nco 6

使用 dplyr 1.0 的解决方案很简单,不需要辅助函数,只需在正确的位置添加一个否定即可。

dat %>% filter(!across(everything(), is.na))
Run Code Online (Sandbox Code Playgroud)

  • 这并没有回答所提出的问题,而是删除*任何*列包含 NA 的所有行,而不仅仅是删除*所有*列包含 NA 的行 (3认同)

sho*_*aco 6

dplyr 1.0.4 引入了if_any()if_all()功能:

dat %>% filter(if_any(everything(), ~!is.na(.)))
Run Code Online (Sandbox Code Playgroud)

或者,更详细:

dat %>% filter(if_any(everything(), purrr::negate(is.na)))
Run Code Online (Sandbox Code Playgroud)

“获取数据并保留任何条目为非 NA 的所有行”