R-排序order(),sort(),rank()

R中有三个排序函数:order(),sort(),rank()

   sort(x)是对向量x进行排序,返回值排序后的数值向量
   rank()是求秩的函数,它的返回值是这个向量中对应元素的“排名”
   而order()的返回值是对应“排名”的元素所在向量中的位置
注意三者返回值的差异。

Example:

> x<-c(1,5,8,2,9,7,4)
> order(x)#x中排第2的数字在原数列中的位置
[1] 1 4 7 2 6 3 5
> sort(x) #x数值排序后x数值本身
[1] 1 2 4 5 7 8 9
> rank(x) #x中数值在排序数列中的排名
[1] 1 4 6 2 7 5 3 


order() function sorts a vector, matrix or data frame.

order(x, decreasing = FALSE, na.last = NA, ...)

x : vector
decreasing : decrease or not
na.last : if TRUE, NAs are put at last position, FALSE at first, if NA, remove them (default)
...  

Sort Vectors:
>x <- c(1,2.3,2,3,4,8,12,43,-4,-1,NA)
>order(x)
 [1] -4.0 -1.0  1.0  2.0  2.3  3.0  4.0  8.0 12.0 43.0

>order(x,decreasing=TRUE)
 [1] 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0

>order(x,decreasing=TRUE, na.last=TRUE)
 [1] 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0   NA

>order(x,decreasing=TRUE, na.last=FALSE)
 [1]   NA 43.0 12.0  8.0  4.0  3.0  2.3  2.0  1.0 -1.0 -4.0

Sort Matrix by one column, following is a csv file example. 

,t1,t2,t3,t4,t5,t6,t7,t8
r1,1,0,1,0,0,1,0,2
r2,1,2,5,1,2,1,2,1
r3,0,0,9,2,1,1,0,1
r4,0,0,2,1,2,0,0,0
r5,0,2,15,1,1,0,0,0
r6,2,2,3,1,1,1,0,0
r7,2,2,3,1,1,1,0,1
>x <- read.csv("ordermatrix.csv",header=T,sep=",");
>x <- x[order(x[,4]),];
>x
"X","t1","t2","t3","t4","t5","t6","t7","t8"
"1","r1",1,0,1,0,0,1,0,2
"4","r4",0,0,2,1,2,0,0,0
"6","r6",2,2,3,1,1,1,0,0
"7","r7",2,2,3,1,1,1,0,1
"2","r2",1,2,5,1,2,1,2,1
"3","r3",0,0,9,2,1,1,0,1
"5","r5",0,2,15,1,1,0,0,0 


Order data frame:
>BOD     #R built-in dataset, Biochemical Oxygen Demand
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

Sort by "demand" column:
>BOD[with(BOD,order(demand)),]
  Time demand
1    1    8.3
2    2   10.3
5    5   15.6
4    4   16.0
3    3   19.0
6    7   19.8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值