r - 获取 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
我想目前它无法在最后两次执行中使用键来查找索引。有什么快速的方法吗?
解决方案
您似乎是 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
推荐阅读
- angular - 有没有人有用于 nativescript + angular 的 RadPieChart 示例?
- java - 来自 AdminInitiateAuth 的 ID 令牌对 API 网关调用无效
- ruby-on-rails - 控制台未出现在 Rails 操作视图中
- amazon-web-services - 如何使用 AWS IAM 策略连接 EC2 和 ECR 跨区域?
- java - frontpage 从 model.addAttribute 获取对象的长类型 id 失去精度
- keras - Keras 函数(K.function)不适用于 RNN(提供的代码)
- scala - scala - 使用正则表达式替换第 2 次和第 4 次出现
- python - 请解释 [1,-1][x < 0]
- android - 如何修复“权限被拒绝”?
- html - 转置的 html 表格未正确对齐