我有一個如下所示的資料框:
Gene Cluster A 0 B 0 C 7 D 7 F 1 G 1 H 2 I 3 L 8 M 8 Z 8
我想按以下順序按數字列“集群”對 data.frame 進行排序:
訂單 = c(1,0,8,7,3,2)
對于一列因素,我通常使用“匹配”,但對于重復數字的數字列,我不知道如何按照我想要的順序對行進行排序。
有人可以幫我嗎?
uj5u.com熱心網友回復:
您使用的想法match是正確的,現在也包括order(.):
dat[order(match(dat$Cluster, c(1,0,8,7,3,2))),]
# Gene Cluster
# 5 F 1
# 6 G 1
# 1 A 0
# 2 B 0
# 9 L 8
# 10 M 8
# 11 Z 8
# 3 C 7
# 4 D 7
# 8 I 3
# 7 H 2
僅供參考,根據?order,
The sort used is _stable_ (except for 'method =
"quick"'), so any unresolved ties will be left in their original
ordering.
所以上面的代碼本身不應該改變Gene其Clusters內的順序。如果您的資料有更多列,您可以隨時在后續引數中添加決勝局;例如,如果您想確保它也在Geneeach 內按字典順序排序Cluster,那么您可以使用
order(match(dat$Cluster, c(1,0,8,7,3,2)), dat$Gene)
# or perhaps more readable
with(dat, match(Cluster, c(1,0,8,7,3,2)), Gene))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/347587.html
標籤:r
