使用dplyr删除所有变量均为NA的行 [英] Remove rows where all variables are NA using dplyr
问题描述
我在看似简单的任务上遇到了一些问题:使用dplyr删除 all 变量为 NA
的所有行。我知道可以使用基数R(删除行在R矩阵中,其中所有数据均为NA 和删除R 中的数据文件的空白行),但我很好奇是否可以使用dplyr来实现。
I'm having some issues with a seemingly simple task: to remove all rows where all variables are NA
using dplyr. I know it can be done using base R (Remove rows in R matrix where all data is NA and Removing empty rows of a data file in R), but I'm curious to know if there is a simple way of doing it using 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))
上面的过滤器
调用确实我想要的东西,但是在我遇到的情况下这是不可行的(因为存在大量变量)。我想可以通过使用 filter _
并首先使用(长)逻辑语句创建一个字符串来做到这一点,但是似乎应该有一种更简单的方法。
The filter
call above does what I want but it's infeasible in the situation I'm facing (as there is a large number of variables). I guess one could do it by using filter_
and first creating a string with the (long) logical statement, but it seems like there should be a simpler way.
另一种方法是使用 rowwise()
和 do()
:
Another way is to use rowwise()
and do()
:
na <- dat %>%
rowwise() %>%
do(tibble(na = !all(is.na(.)))) %>%
.$na
filter(dat, na)
但这看起来不太好,尽管可以完成工作。还有其他想法吗?
but that does not look too nice, although it gets the job done. Other ideas?
推荐答案
自dplyr 0.7.0起,存在新的作用域过滤动词。使用filter_any可以轻松地过滤至少包含一个非缺失列的行:
Since dplyr 0.7.0 new, scoped filtering verbs exists. Using filter_any you can easily filter rows with at least one non-missing column:
dat %>% filter_all(any_vars(!is.na(.)))
使用@hejseb基准测试算法,看来该解决方案同样有效如f4。
Using @hejseb benchmarking algorithm it appears that this solution is as efficient as f4.
这篇关于使用dplyr删除所有变量均为NA的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!