【发布时间】:2015-12-18 03:05:45
【问题描述】:
这似乎是一个显而易见的问题,但我觉得我做错了。我有一个字符串向量,我只想在 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]
获取索引,但仍然没有解决我试图描绘的问题。
【问题讨论】:
标签: r data.table binary-search