如果我使用order()indata.frame和 ,我會得到不同的結果data.table。例如:
A <- data.frame(one=c("k"),two=c("3_28","31_60","48_68"))
B <- as.data.table(A)
A[order(A$one,A$two),]
one two
1 k 3_28
2 k 31_60
3 k 48_68
B[order(B$one, B$two),]
one two
1: k 31_60
2: k 3_28
3: k 48_68
我必須承認這有點令人震驚,因為多年來我一直在假設相同的結果order()。我想我需要檢查很多代碼!data.framedata.table
有什么方法可以確保在和order()中給出相同的結果?data.framedata.table
如果這種行為差異已經眾所周知,我深表歉意,這只是我無知的一個例子。
uj5u.com熱心網友回復:
在操作內部使用時data.table,order(..)使用data.table:::forder. 根據data.table小插圖的介紹:
order() 在內部進行了優化
character我們可以在 a的框架內的列上使用“-”data.table來按降序排序。此外,
order(...)在 a 的框架內data.table使用data.table內部快速基數順序forder()。與 R 相比,這種排序提供了如此引人注目的改進,base::order以至于 R 專案data.table在 2016 年采用該演算法作為 R 3.3.0 的默認排序,請參閱?sort和R Release NEWS。
看到差異的關鍵是它使用“快速基數順序”。但是,如果您看到base::order,它有一個method=論點
method: the method to be used: partial matches are allowed. The
default ('"auto"') implies '"radix"' for short numeric
vectors, integer vectors, logical vectors and factors.
Otherwise, it implies '"shell"'. For details of methods
'"shell"', '"quick"', and '"radix"', see the help for 'sort'.
由于您的第二列data.table不是numeric, integer, logical, 或之一factor,因此base::order使用"shell"排序方法,這會產生不同的結果。
但是,如果我們強制base::order使用method="radix",我們會得到相同的結果。
order(A$two)
# [1] 1 2 3
order(A$two, method="radix")
# [1] 2 1 3
A[order(A$one, A$two, method = "radix"),]
# one two
# 2 k 31_60
# 1 k 3_28
# 3 k 48_68
您可以使用以下命令影響相同的排序base::order:
B[base::order(B$one,B$two),]
# one two
# <char> <char>
# 1: k 3_28
# 2: k 31_60
# 3: k 48_68
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467209.html
上一篇:通過值獲取頂點
