data.table 中过滤的奇怪行为

Strange behavior for filtering in data.table

我偶然发现了奇怪的数据 table i 行为 returns 一行 NAs 我希望有一个空数据 table .参见:

a = data.table(a = 1, d = NA) 
a[!is.na(a) & d == "3"] 
#     a  d
# 1: NA NA

我希望这里的结果是空数据 table。 比较对象:

a = data.table(a = c(1,2), d = c(NA,3))
a[!is.na(a) & d == "3"] 
#    a d
# 1: 2 3

不过,这不会产生具有 NA 值的额外行。
这是 data.table 中的错误还是有人可以解释此行为背后的某些逻辑?

不知道是不是bug,好像跟你的变量d的类型有关。

a = data.table(a = 1, d = NA) 
str(a)
# Classes ‘data.table’ and 'data.frame':    1 obs. of  2 variables:
#  $ a: num 1
#  $ d: logi NA
#  - attr(*, ".internal.selfref")=<externalptr> 

a[!is.na(a) & d == "3"] # this returns NAs
#     a  d
# 1: NA NA

a[!is.na(a) & !is.na(d)] # this returns nothing
# Empty data.table (0 rows) of 2 cols: a,d

这个也有效:

a = data.table(a = 1, d = 4) 
str(a)
# Classes ‘data.table’ and 'data.frame':    1 obs. of  2 variables:
#  $ a: num 1
#  $ d: num 4
#  - attr(*, ".internal.selfref")=<externalptr> 

a[!is.na(a) & d == "3"]
#     Empty data.table (0 rows) of 2 cols: a,d

看起来如果一个变量是逻辑类型,它就不能与另一种类型和 returns NA 进行比较。 但是,使用 dplyr 包似乎可以工作:

library(dplyr)

a = data.table(a = 1, d = NA) 
a %>% filter(!is.na(a) & d == "3")
# Empty data.table (0 rows) of 2 cols: a,d

与子集命令相同:

subset(a, !is.na(a) & d == "3")
# Empty data.table (0 rows) of 2 cols: a,d

感谢 ping @SergiiZaskaleta。我忘了更新这个问题,但这已经在前一段时间修复了,with this commit.

来自NEWS

  1. Subsets using logical expressions in i never returns all-NA rows. Edge case DT[NA] is now fixed, #1252. Thanks to @sergiizaskaleta.