r - 在 data.table 中查找匹配项的行索引(我可以进行二分搜索吗?)

标签 r data.table binary-search

这似乎是一个如此明显的问题,但我觉得我做错了。我有一个字符串向量,我只想在 data.table 中找到匹配的行索引。 data.table 由我想要匹配的列作为键,所以,我认为我应该能够使用二分搜索来找到匹配的索引。

要遵循的示例:

在这里,我有一个 data.table,以列 c2 为键和一个字符串向量,new_dat ,我想找到行索引。

library(data.table)

## Example data, a keyed data.table
dat <- data.table(c1=1:10, c2=letters[1:10], key='c2')

## Match at some indices (keyed column so should be binary search?)
new_dat <- c('d', 'j')

## This doesn't feel right -- I don't think this is taking advantage of the
## data.table ordering at all
## Tried some dumb stuff like dat[match(new_dat, c2, 0L), .I]
dat[match(new_dat, c2, 0L), ]  # only want the index of the matches
#    c1 c2
# 1:  4  d
# 2: 10  j

## So, this is the desired result,
## but this is just doing ordinary linear search (I say w/o actually looking at the code)
match(new_dat, dat[['c2']], 0L)
# [1]  4 10

埃迪德

我才意识到我可以做到,
dat[, ind := 1:.N][match(new_dat, c2, 0L), ind]

获取索引,但仍然没有解决我试图描绘的问题。

最佳答案

为了找到行索引(虽然不使用 by 参数分组),您可以指定 which = TRUE在执行二元连接时

options(datatable.verbose = TRUE) # Setting to TRUE so we can see the binary join being triggered
dat[new_dat, which = TRUE]
# Starting bmerge ...done in 0 secs <~~ binary join triggered
# [1]  4 10

(这也可以在不创建 c1 的情况下工作,因为它根本不使用该列)

而且,如果您只想执行普通的二元连接并查看所有列中的所有值,则不需要使用 match或者创建一个索引,就做
dat[new_dat]
# Starting bmerge ...done in 0 secs <~~ binary join triggered
#    c1 c2
# 1:  4  d
# 2: 10  j

一般来说,只要你的数据是键控的(或者你使用 on 参数来加入) new_dat不属于类 integernumeric , data.table即使 new_dat 也会自动触发二进制连接传递给 i第一个参数 没有 被包裹成.J .虽然,如果 new_dat是上述类之一,data.table将尝试执行行索引。因此,您将需要使用 dat[.(new_dat), which = TRUE]dat[J(new_dat), which = TRUE]为了给力bmerge而是行索引。

关于r - 在 data.table 中查找匹配项的行索引(我可以进行二分搜索吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347928/

相关文章:

r - 动态子集数据表

将变量名称向量中的 Inf/-Inf 值替换为类似命名的变量向量 (substr/grep/gsub) 中的值

c# - 比普通二进制搜索更快地搜索排序列表的自定义选项

c++ - 二进制搜索以在 STL C++ 多重集中查找小于或等于的值

r - R(dplyr)中的Left Join-观察太多?

r - 如何通过 R 中的变量计算疾病患病率

r - 检查传递的参数是否存在

r - 使用 is.null() 有条件地子集 r data.table

r - 如何有条件地选择每组中的一行/行?

c - 如何修复 C 中字符串数组的二分搜索