data.table:如何对一个键处的两个(数字)值进行二进制搜索:包括示例 [英] data.table: How to do binary search for two (numeric) values at one key: example included
问题描述
示例数据:
library(data.table)
DT <- data.table(a = c(1, 3, 5, 9, 15),
b = c("a", "c", "d", "e", "f"))
我想得到两行,即 a == 3 | a == 9
,即
# a b
# 3 c
# 9 e
我知道是否这样做: DT [,a: = as.character(a)]
然后 setkey(DT,a)
和 DT [c( 3, 9)]
,我可以得到想要的结果。但是我想知道,是否还有其他方法可以执行这种二进制搜索而无需预先将 a
更改为字符?
I know if I do: DT[, a:=as.character(a)]
then setkey(DT, a)
and DT[c("3", "9")]
, I can get the wanted result. But I would like to know, if there are other methods to do this kind of binary search without changing a
to character in advance?
推荐答案
您无需将其转换为字符向量(尽管整数会更有意义)
You don't need to convert it into a character vector (although integer would make more sense)
DT <- data.table(a = c(1, 3, 5, 9, 15), b = c("a", "c", "d", "e", "f"))
setkey(DT, a)
DT[J(c(3, 9))]
此外,如果您使用的是CRAN中的最新版本,则第二次在i中使用a将自动使用二进制搜索
Moreover, if you have the latest version in CRAN, the second time you use a in i will automatically uses binary search
这篇关于data.table:如何对一个键处的两个(数字)值进行二进制搜索:包括示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!