其他分享
首页 > 其他分享> > 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

 

标签:多列,98,##,76,scores,排序,order
来源: https://www.cnblogs.com/liujiaxin2018/p/16228270.html