2014-02-18 54 views
1

我發現在data.table()裏面,order函數按組枚舉行,而最初的想法是查看指定組內每個觀察值的等級。data.table函數內部錯誤的結果

這裏是一個可再現的例子:

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) 

結果(因爲我得到它):

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 

這顯然是錯誤的。 我做錯了什麼,以及如何在data.table中使用order()?

謝謝!

+0

我想你實際上是在尋找'rank'不'order'。也許是這樣的:'test [,item_position:= rank(a,ties.method =「first」),by = b] []'? – A5C1D2H2I1M1N2O1R2T1

+1

@eddi,有趣的是,他們確實使用'set.seed',但我得到完全不同的結果:-) – A5C1D2H2I1M1N2O1R2T1

+1

@eddie對不起,我的壞,修復了結果。它仍然不是我所期待的,但我希望這次它匹配:) – Loiisso

回答

1

我想你對order做的一些誤解。一切從你的描述,你實際上是在尋找rank

test[, B_S := rank(-a, ties.method="first"), by = b][] ## Big to Small 
#  a  b B_S 
# 1: -19 group_1 4 
# 2: 6 group_1 3 
# .. SNIP .. 
# 9: 17 group_2 2 
# 10: -9 group_2 4 
test[, S_B := rank(a, ties.method="first"), by = b][] ## Small to big 
#  a  b B_S S_B 
# 1: -19 group_1 4 2 
# 2: 6 group_1 3 3 
# .. SNIP .. 
# 9: 17 group_2 2 4 
# 10: -9 group_2 4 2 
setkey(test, b, S_B) 
test 
#  a  b B_S S_B 
# 1: -25 group_1 5 1 
# 2: -19 group_1 4 2 
# 3: 6 group_1 3 3 
# 4: 10 group_1 2 4 
# 5: 48 group_1 1 5 
# 6: -25 group_2 5 1 
# 7: -9 group_2 4 2 
# 8: 15 group_2 3 3 
# 9: 17 group_2 2 4 
# 10: 22 group_2 1 5 

沒有什麼錯的順序輸出(除了它是你預期的不是)。考慮以下幾點:

x <- c(-19, 6, -25, 48, 10) 
order(x, decreasing=TRUE) 
# [1] 4 5 2 1 3 
cbind(x, order(x, decreasing=TRUE)) 
#  x 
# [1,] -19 4 
# [2,] 6 5 
# [3,] -25 2 
# [4,] 48 1 
# [5,] 10 3 

這是完全一樣的東西,你在你的答案data.table獲得。要查看關於order功能的更多信息,請查看此Q和A組:Understanding the order() function

1

Ananda的解決方案是更小數據集的方法。對於較大的,當速度成爲一個問題,你可能會想使用data.tablesetkey代替:

test[, idx := .I]   # save index to reorder later 
setkey(test, b, a)   # order the way we want 
test[, pos := 1:.N, by = b] # save the positions per group 
setkey(test, idx)   # back to original order 
+0

你可能也可以直接使用內部的快速命令功能(而不是訴諸'setkey'),但我真的不知道在使用哪些函數時 – eddi