不确定您是否已经知道行位置,或者是否要搜索它们。无论哪种方式,这都应该涵盖两者。
require(data.table)
set.seed(1)
DT = data.table(a=sample(1:1000,20), b=sample(1:1000,20))
setkey(DT,a)
DT
# a b
# 1: 62 338
# 2: 175 593
# 3: 201 267
# 4: 204 478
# 5: 266 935
# 6: 372 212
# 7: 374 711
# 8: 380 184
# 9: 491 659
# 10: 572 651
# 11: 625 863
# 12: 657 380
# 13: 679 488
# 14: 707 782
# 15: 760 816
# 16: 763 404
# 17: 894 385
# 18: 906 126
# 19: 940 14
# 20: 976 107
r = c(201,380,760)
starts = DT[J(r),which=TRUE] # binary search for items
# skip if the starting row numbers are known
starts
# [1] 3 8 15
选项1:制作行号序列,连接并在其中进行一次查找DT
(无需键或二进制搜索即可按行号进行选择):
DT[unlist(lapply(starts,seq.int,length=5))]
# a b
# 1: 201 267
# 2: 204 478
# 3: 266 935
# 4: 372 212
# 5: 374 711
# 6: 380 184
# 7: 491 659
# 8: 572 651
# 9: 625 863
# 10: 657 380
# 11: 760 816
# 12: 763 404
# 13: 894 385
# 14: 906 126
# 15: 940 14
选项 2:列出 data.table 子集,然后将rbind
它们放在一起。这比选项 1 效率低,但为了完整性:
L = lapply(starts,function(i)DT[seq.int(i,i+4)])
L
# [[1]]
# a b
# 1: 201 267
# 2: 204 478
# 3: 266 935
# 4: 372 212
# 5: 374 711
#
# [[2]]
# a b
# 1: 380 184
# 2: 491 659
# 3: 572 651
# 4: 625 863
# 5: 657 380
#
# [[3]]
# a b
# 1: 760 816
# 2: 763 404
# 3: 894 385
# 4: 906 126
# 5: 940 14
rbindlist(L) # more efficient that do.call("rbind",L). See ?rbindlist.
# a b
# 1: 201 267
# 2: 204 478
# 3: 266 935
# 4: 372 212
# 5: 374 711
# 6: 380 184
# 7: 491 659
# 8: 572 651
# 9: 625 863
# 10: 657 380
# 11: 760 816
# 12: 763 404
# 13: 894 385
# 14: 906 126
# 15: 940 14