只是想知道是否有一种简化的方法可以将data.table子集化。基本上我有一张桌子,上面有数百万行和数百列列。我想基于整数col / s对其进行子集化,该整数具有我定义的范围之间的值。
我想知道是否将相关列设置为键,这将是二进制搜索,但是不确定是否可以找到一系列值之间的行。
人为的例子如下。
> n = 1e7
> dt <- data.table(a=rnorm(n),b=sample(letters,replace=T,n))
> system.time(subset(dt, a > 1 & a < 2))
user system elapsed
1.596 0.000 1.596
> system.time(dt[a %between% c(1,2)])
user system elapsed
1.168 0.000 1.168
可以这样做吗?
setkey(dt,a)
dt[ ] : get me the rows between 1 and 2 values of the key
谢谢!
-阿比
最佳答案
如果您确实在a
上设置了密钥(这将需要一些时间(n=1e7
在我的计算机上为14.7秒),
那么您可以使用滚动联接来确定感兴趣区域的开始和结束。
# thus the following will work.
dt[seq.int(dt[.(1),.I,roll=-1]$.I, dt[.(2), .I, roll=1]$.I)]
n = 1e7
dt <- data.table(a=rnorm(n),b=sample(letters,replace=T,n))
system.time(setkey(dt,a))
# This does take some time
# user system elapsed
# 14.72 0.00 14.73
library(microbenchmark)
f1 <- function() t1 <- dt[floor(a) == 1]
f2 <- function() t2 <- dt[a >= 1 & a <= 2]
f3 <- function() {t3 <- dt[seq.int(dt[.(1),.I,roll=-1]$.I, dt[.(2), .I, roll=1]$.I)] }
microbenchmark(f1(),f2(),f3(), times=10)
# Unit: milliseconds
# expr min lq median uq max neval
# f1() 371.62161 387.81815 394.92153 403.52299 489.61508 10
# f2() 529.62952 536.23727 544.74470 631.55594 634.92275 10
# f3() 65.58094 66.34703 67.04747 75.89296 89.10182 10
现在是“快速”,但是因为我们花了更早的时间来设置密钥。
添加@eddi的基准测试方法
f4 <- function(tolerance = 1e-7){ # adjust according to your needs
start = dt[J(1 + tolerance), .I[1], roll = -Inf]$V1
end = dt[J(2 - tolerance), .I[.N], roll = Inf]$V1
if (start <= end) dt[start:end]}
microbenchmark(f1(),f2(),f3(),f4(), times=10)
# Unit: milliseconds
# expr min lq median uq max neval
# f1() 373.3313 391.07479 440.07025 488.54020 491.48141 10
# f2() 523.2319 530.11218 533.57844 536.67767 629.53779 10
# f3() 65.6238 65.71617 66.09967 66.56768 83.27646 10
# f4() 65.8511 66.26432 66.62096 83.86476 87.01092 10
Eddi的方法稍微有点安全,因为它可以处理浮点公差。