test <- data.table(x=sample.int(10, 1000000, replace=TRUE))
y <- test$x
test[,.N, by=x] # fast
test[,.N, by=y] # extremely slow
Why it is slow on the second case?
It is even faster to do this:
test[,y:=y]
test[,.N, by=y]
test[,y:=NULL]
It looks as if it is poorly optimized?
Seems like I forgot to update this post.
Fixed
#5106
whereDT[, .N, by=y]
wherey
is a vector withlength(y) = nrow(DT)
, buty
is not a column inDT
. Thanks tocolinfang
for reporting.
require(data.table)
test <- data.table(x=sample.int(10, 1000000, replace=TRUE))
y <- test$x
system.time(ans1 <- test[,.N, by=x])
# user system elapsed
# 0.015 0.000 0.016
system.time(ans2 <- test[,.N, by=y])
# user system elapsed
# 0.015 0.000 0.015
setnames(ans2, "y", "x")
identical(ans1, ans2) # [1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With