首页 > 解决方案 > 获取 data.table 中键的索引

问题描述

有没有一种快速的方法可以从 data.table 中获取值的索引?我已将列设置为键,但是,我很难找到获取其索引的有效方法?

x <- sample(letters, 200, replace = TRUE)
y <- rnorm(200)
DT <- data.table(x, y, key = "x")
df <- data.frame(x, y)

执行时间处理时间:

system.time(for(i in 1:1000) DT[.("g"), which= TRUE]) # 0.3 sec
system.time(for(i in 1:1000) which(DT$x == "g")) # 0.004 sec
system.time(for(i in 1:1000) which(df$x == "g")) # 0.004 sec

我想目前它无法在最后两次执行中使用键来查找索引。有什么快速的方法吗?

标签: rdata.table

解决方案


您似乎是 1) 运行到使用时间[.data.table和 2) 可能会运行大量开销来启动仅 200 行的连接操作。增加到 2,000,000 行会导致DT[.("g"), which = TRUE]非常快。

library(data.table)
x <- sample(letters, 200, replace = TRUE)
y <- rnorm(200)
DT <- data.table(x, y, key = "x")
bench::mark(which(DT$x == "g"),
            DT[.("g"), which = TRUE])

## # A tibble: 2 x 13
##   expression                   min  median `itr/sec` mem_alloc
##   <bch:expr>               <bch:t> <bch:t>     <dbl> <bch:byt>
## 1 which(DT$x == "g")         7.9us  11.2us    88385.    1.66KB
## 2 DT[.("g"), which = TRUE] 735.8us 905.8us     1010.   64.73KB

## 20,000 rows:

## # A tibble: 2 x 13
##   expression                 min median `itr/sec` mem_alloc
##   <bch:expr>               <bch> <bch:>     <dbl> <bch:byt>
## 1 which(DT$x == "g")       251us  265us     3654.   159.5KB
## 2 DT[.("g"), which = TRUE] 744us  907us      879.    67.8KB

## 2,000,000 rows:

## # A tibble: 2 x 13
##   expression                   min median `itr/sec` mem_alloc
##   <bch:expr>               <bch:t> <bch:>     <dbl> <bch:byt>
## 1 which(DT$x == "g")       21900us 24.9ms      40.6    15.6MB
## 2 DT[.("g"), which = TRUE]   868us  1.1ms     724.    366.1KB

推荐阅读