data.table:如何在一个键执行二进制搜索两个(数值)值:exemple包括 [英] data.table: How to do binary search for two (numeric) values at one key: exemple included
本文介绍了data.table:如何在一个键执行二进制搜索两个(数值)值:exemple包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
范例资料:
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的最新版本,自动使用二进制搜索
Moreover, if you have the latest version in CRAN, the second time you use a in i will automatically uses binary search
这篇关于data.table:如何在一个键执行二进制搜索两个(数值)值:exemple包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文