1. 程式人生 > 其它 >R語言中order命令依據多列對資料框進行排序

R語言中order命令依據多列對資料框進行排序

 

1、問題

> x <- c(1, 3, 2, 1, 2, 3)
> y <- c(5, 7, 6, 8, 9, 6)
> order(x)                  ## 返回了排序的索引
[1] 1 4 3 5 2 6
> order(y)
[1] 1 3 6 2 4 5
> order(x, y)               ## 當向量x相同時,此時再依據y向量進行排序,即優先x排序,當x相同時,依據y排序, 當x為3時,此時y向量的6小於7,因此返回索引6.
[1] 1 4 3 5 6 2
> order(y, x)               ## 先y後x
[
1] 1 3 6 2 4 5

 

2、例項

> name <- c('James','John','Luka','Green','Lisa','Curry','Jimmy','Xiaojie')
> R_scores <- c(88,68,76,76,93,76,98,98)
> Linux_scores <- c(78,63,76,82,81,63,92,95)
> scores <- data.frame(name=name,R_scores=R_scores,Linux_scores=Linux_scores)
> scores                    ## 測試資料框
name R_scores Linux_scores
1 James 88 78 2 John 68 63 3 Luka 76 76 4 Green 76 82 5 Lisa 93 81 6 Curry 76 63 7 Jimmy 98 92 8 Xiaojie 98 95 > scores[order(scores$R_scores),] ## 依據第二列進行排序
name R_scores Linux_scores
2 John 68 63 3 Luka 76 76 4 Green 76 82 6 Curry 76 63 1 James 88 78 5 Lisa 93 81 7 Jimmy 98 92 8 Xiaojie 98 95 > scores[order(scores$R_scores, scores$Linux_scores),] ## 優先依據第2列排序,當第二列有相同項時,再依據第三列進行排序 name R_scores Linux_scores 2 John 68 63 6 Curry 76 63 3 Luka 76 76 4 Green 76 82 1 James 88 78 5 Lisa 93 81 7 Jimmy 98 92 8 Xiaojie 98 95

 

出處:https://mp.weixin.qq.com/s?__biz=MzAxMDkxODM1Ng==&mid=2247513582&idx=2&sn=77228bc56c3411e84afa457ff14425c4&chksm=9b4bf555ac3c7c434fa9c0cfe7d16744d6a361b3827aa930dbd334c36bc5d96336347067743e&mpshare=1&scene=23&srcid=0505TCPhIaQDpxUIBnPgUYtG&sharer_sharetime=1651685667859&sharer_shareid=50b75c6a886e09824b582fb782a7678b#rd