为什么 dplyr 的过滤器会从因子变量中删除 NA 值? [英] Why does dplyr's filter drop NA values from a factor variable?

查看:16
本文介绍了为什么 dplyr 的过滤器会从因子变量中删除 NA 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 dplyr 包中的 filter 删除因子变量的级别时,filter 也会删除 NA 值.举个例子:

When I use filter from the dplyr package to drop a level of a factor variable, filter also drops the NA values. Here's an example:

library(dplyr)
set.seed(919)
(dat <- data.frame(var1 = factor(sample(c(1:3, NA), size = 10, replace = T))))
#    var1
# 1  <NA>
# 2     3
# 3     3
# 4     1
# 5     1
# 6  <NA>
# 7     2
# 8     2
# 9  <NA>
# 10    1

filter(dat, var1 != 1)
#   var1
# 1    3
# 2    3
# 3    2
# 4    2

这似乎并不理想——我只想删除 var1 == 1 的行.

This does not seem ideal -- I only wanted to drop rows where var1 == 1.

看起来这是因为任何 NA 的比较返回NA,然后删除 filter.因此,例如, filter(dat, !(var1 %in% 1)) 产生正确的结果.但是有没有办法告诉 filter 不要删除 NA 值?

It looks like this is occurring because any comparison with NA returns NA, which filter then drops. So, for example, filter(dat, !(var1 %in% 1)) produces the correct results. But is there a way to tell filter not to drop the NA values?

推荐答案

你可以使用这个:

 filter(dat, var1 != 1 | is.na(var1))
  var1
1 <NA>
2    3
3    3
4 <NA>
5    2
6    2
7 <NA>

它不会.

同样只是为了完成,删除 NAs 是 filter 的预期行为,如下所示:

Also just for completion, dropping NAs is the intended behavior of filter as you can see from the following:

test_that("filter discards NA", {
  temp <- data.frame(
    i = 1:5,
    x = c(NA, 1L, 1L, 0L, 0L)
  )
  res <- filter(temp, x == 1)
  expect_equal(nrow(res), 2L)
})

上述测试取自 github.

This test above was taken from the tests for filter from github.

这篇关于为什么 dplyr 的过滤器会从因子变量中删除 NA 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆