I have found that inside data.table(), order function enumerates rows by groups, while the original idea is to see rank of each observation inside specified groups.
Here is a reproducable example:
require(data.table)
N <- 10
set.seed(1)
test <- data.table(
a = round(rnorm(N,mean=0, sd = 30),0),
b = c(rep('group_1', N/2 ),rep('group_2', N/2))
)
test <- test[, item_position := order(a, decreasing = T), by=list(b)]
setkey(test, b, item_position)
View(test)
The result (as I get it):
test
a b item_position
1: 48 group_1 1
2: -25 group_1 2
3: 10 group_1 3
4: -19 group_1 4
5: 6 group_1 5
6: -9 group_2 1
7: 22 group_2 2
8: -25 group_2 3
9: 15 group_2 4
10: 17 group_2 5
Which is obviously wrong. What am I doing wrong, and how can I use order() inside data.table?
Thank you!