R语言排序三个基本函数:sort(),rank(),order()的用法
1、sort()
用法:sort(a,decreasing=T) 或 sort(a,decreasing=T)
其中,a为要排序的向量

# sort()排序,排序结果不可逆转
# 默认是升序
# decreasing为TRUE,表示降序
# decreasing为FALSE,表示升序
#排序后并不会修改原对象的值

#示例如下:
> a <- c(3,9,16,6,7,4,22,5,10,13)
> #sort()默认为从小到大(升序)排序,等同于decreasing=FALSE
> sort(a)
 [1]  3  4  5  6  7  9 10 13 16 22
> sort(a,decreasing = F)
 [1]  3  4  5  6  7  9 10 13 16 22
> #decreasing=TRUE,为从大到小(降序)排序
> sort(a,decreasing = T)
 [1] 22 16 13 10  9  7  6  5  4  3

#排序并不会修改原对象的值,a仍为原来未排序的a
> a
 [1]  3  9 16  6  7  4 22  5 10 13

2、order()
函数说明:返回的值表示位置,默认是升序,依次对应的是向量的最小值、次小值、第三小值…最大值

用法:order(a), a为要排序的向量
order(… = data, na.last = TRUE,decreasing = TRUE)
… 表示待排序向量
na.last 表示时候将NA值放在最后面(默认排序忽略NA)
decreasing 表示是否按照降序排序,默认升序。

> a <- c(3,9,16,6,7,4,22,5,10,13)
> order(a)
 [1]  1  6  8  4  5  2  9 10  3  7
#说明:在向量a中,3是第一小的数,位置下标为1;4是第二小的数,位置下标为6;最大的数是22,位置下标为7

#a[order(a)] 等同于sort(a)
> a[order(a)] 
 [1]  3  4  5  6  7  9 10 13 16 22

3、rank()
用法:rank(a)
函数说明:指出当前向量中各元素大小的排名,默认升序
函数还有其他的参数:rank(x = data, na.last = TRUE)
x 表示待排序的向量
na.last 表示是否排序时是否将NA放在最后面,默认忽略NA

> a
 [1]  3  9 16  6  7  4 22  5 10 13
> sort(a)
 [1]  3  4  5  6  7  9 10 13 16 22
> rank(a)
 [1]  1  6  9  4  5  2 10  3  7  8
 #说明:向量a中的第一个数为3,是最小的,故排名为1;第二个数是9,是第六小的数,排名为6

4、sort()、order()、rank()总体比较

> a <- c(3,9,16,6,7,4,22,5,10,13)
> a
 [1]  3  9 16  6  7  4 22  5 10 13
> sort(a) #将a**从小到大排序并列出**
 [1]  3  4  5  6  7  9 10 13 16 22
> order(a) #返回从小到大的数的**位置下标**,a[order(a)]=sort(a)
 [1]  1  6  8  4  5  2  9 10  3  7
> rank(a) #返回a中**每个数的排名(从小到大)**
 [1]  1  6  9  4  5  2 10  3  7  8
> a
 [1]  3  9 16  6  7  4 22  5 10 13
#注意:经过sort()、order()、rank()排序后,a不改变
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐