[英]How to compute the ranking (of dates) by groups faster with data.table and lubridate?
我需要按組計算日期的排名。 有很多小團體。
library(data.table)
library(lubridate)
library(microbenchmark)
set.seed(1)
NN <- 1000000
EE <- 10
# Just an example.
todo <- data.table(id=paste0("ID",rep(1:NN, each=EE)),
val=dmy("1/1/1980") + sample(1:14000,NN*EE,replace=T))
# I want to benchmark this:
todo[,ord := frank(val, ties.method="first"), by=id]
為了比較它,您可以嘗試使用更小的 NN,時間是線性的。
對於 NN = 100 萬,需要 560 秒。
有什么方法可以更快地做到這一點?
我一直在使用 lubridate,但我可以使用您建議的任何庫。
在我的實際問題中,每個 ID 中的行數不是恆定的。
我相信這是由於許多小組多次調用frank
的開銷(下面的 memory 用法應該會給您關於瓶頸的提示)。 這是另一種選擇:
DT1[order(id, val), ord := rowid(id)]
計時碼:
library(data.table)
set.seed(1L)
NN <- 1e6
EE <- 10
todo <- data.table(id=paste0("ID",rep(1:NN, each=EE)),
val=as.IDate("1980-01-01") + sample(1:14000,NN*EE,replace=T))
DT0 <- copy(todo)
DT1 <- copy(todo)
bench::mark(
todo[, ord := frank(val, ties.method="first"), by=id],
DT0[, ord := rank(unclass(val), ties.method = "first"), by = id],
DT1[order(id, val), ord := rowid(id)])
all.equal(todo$ord, DT0$ord)
# [1] TRUE
all.equal(todo$ord, DT1$ord)
# [1] TRUE
時間:
expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time
<bch:expr> <bch> <bch:> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <lis>
1 todo[, `:=`(ord, frank(val, ties.method = "first")), by = id] 6.32m 6.32m 0.00264 15.7GB 0.177 1 67 6.32m <df[,~ <df[,~ <bch~
2 DT0[, `:=`(ord, rank(unclass(val), ties.method = "first")), by = id] 1.12m 1.12m 0.0149 99.3MB 0.969 1 65 1.12m <df[,~ <df[,~ <bch~
3 DT1[order(id, val), `:=`(ord, rowid(id))] 7.85s 7.85s 0.127 236.8MB 0 1 0 7.85s <df[,~ <df[,~ <bch~
如果我們按order
刪除id
會更快:
DT1[order(val), ord := rowid(id)]
計時碼:
bench::mark(DT0[order(id, val), ord := rowid(id)],
DT1[order(val), ord := rowid(id)])
all.equal(DT0$ord, DT1$ord)
# [1] TRUE
時間:
# A tibble: 2 x 13
expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list>
1 DT0[order(id, val), `:=`(ord, rowid(id))] 7.44s 7.44s 0.134 237MB 0 1 0 7.44s <df[,3] [10,000,000 x 3]> <df[,3] [15 x 3]> <bch:tm> <tibble [1 x 3]>
2 DT1[order(val), `:=`(ord, rowid(id))] 4.66s 4.66s 0.215 237MB 0 1 0 4.66s <df[,3] [10,000,000 x 3]> <df[,3] [14 x 3]> <bch:tm> <tibble [1 x 3]>
我嘗試了一些設置,發現使用rank(unclass(val), ties.method = "first")
的最大改進 - 相當於frank()
的基本 R 。 由於某種原因,它在涉及分組時優於frank()
。
# Output from microbenchmark::microbenchmark()
Unit: seconds
expr min lq mean median uq max neval
todo[, frank(val, ties.method = "first"), by = id] 599.8309 599.8309 599.8309 599.8309 599.8309 599.8309 1
todo[, rank(unclass(val), ties.method = "first"), by = id] 111.4396 111.4396 111.4396 111.4396 111.4396 111.4396 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.