gpt4 book ai didi

r - 由 NaN 设置的 data.table 子集不起作用

转载 作者:行者123 更新时间:2023-12-04 18:43:32 24 4
gpt4 key购买 nike

我在数据表中有一列 NaN值。就像是:

my.dt <- data.table(x = c(NaN, NaN, NaN, .1, .2, .2, .3), y = c(2, 4, 6, 8, 10, 12, 14))
setkey(my.dt, x)

我可以使用 J()函数来查找 x 所在的所有实例列等于 0.2
> my.dt[J(.2)]

x y
1: 0.2 10
2: 0.2 12

但是如果我尝试用 NaN 做同样的事情它不起作用。
> my.dt[J(NaN)]

x y
1: NaN NA

我希望:
     x  y
1: NaN 2
2: NaN 4
3: NaN 6

是什么赋予了?我在 data.table 文档中找不到任何内容来解释为什么会发生这种情况(尽管可能只是我不知道要查找什么)。有什么办法可以得到我想要的吗?最后,我想替换所有 NaN值为零,使用类似 my.dt[J(NaN), x := 0]

最佳答案

这是一个快速的解决方法,它在很大程度上依赖于内部实际发生的事情(使代码有点脆弱)。因为内部NaN只是一个非常非常负的数字,它将永远在您的data.table 前面当你setkey .我们可以使用该属性来隔离这些条目,如下所示:

# this will give the index of the first element that is *not* NaN
my.dt[J(-.Machine$double.xmax), roll = -Inf, which = T]

# this is equivalent to my.dt[!is.nan(x)], but much faster
my.dt[seq_len(my.dt[J(-.Machine$double.xmax), roll = -Inf, which = T] - 1)]

以下是 Ricardo 样本数据的基准:
my.dt <- as.data.table(replicate(20, sample(100, 1e5, TRUE)))
setnames(my.dt, 1, "ID")
my.dt[sample(1e5, 1e3), ID := NA]
setkey(my.dt, ID)

# NOTE: I have to use integer max here - because this example has integers
# instead of doubles, so I'll just add simple helper function (that would
# likely need to be extended for other cases, but I'm just dealing with the ones here)
minN = function(x) if (is.integer(x)) -.Machine$integer.max else -.Machine$double.xmax

library(microbenchmark)
microbenchmark(normalJ = my.dt[J(1)],
naJ = my.dt[seq_len(my.dt[J(minN(ID)), roll = -Inf, which = T] - 1)])
#Unit: milliseconds
# expr min lq median uq max neval
# normalJ 1.645442 1.864812 2.120577 2.863497 5.431828 100
# naJ 1.465806 1.689350 2.030425 2.600720 10.436934 100

在我的测试中,以下 minN函数还包括字符和逻辑向量:
minN = function(x) {
if (is.integer(x)) {
-.Machine$integer.max
} else if (is.numeric(x)) {
-.Machine$double.xmax
} else if (is.character(x)) {
""
} else if (is.logical(x)) {
FALSE
} else {
NA
}
}

你会想要添加 mult = 'first' ,例如:
my.dt[seq_len(my.dt[J(minN(colname)), roll = -Inf, which = T, mult = 'first'] - 1)]

关于r - 由 NaN 设置的 data.table 子集不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com