第四章:数据操作Ⅰ 第八节:数据排序

使用sort()与order()函数可以对数据进行排序,sort()函数直接对给定数据进行排序,order()函数返回排序后数据的原始位置

一、sort()函数

例如:

R 复制代码
> x<-c(20,11,33,50,47)
> sort(x)
[1] 11 20 33 47 50
> sort(x,decreasing = TRUE)
[1] 50 47 33 20 11

二、order()函数

Order()函数返回排序以后的各元素数据在原始数据组中的位置索引

例如

R 复制代码
> x<-c(20,11,33,50,47)
> order(x)
[1] 2 1 3 5 4

若想实现降序,则依然采用decreasing参数进行

R 复制代码
> x<-c(20,11,33,50,47)
> order(x,decreasing = TRUE)
[1] 4 5 3 1 2

我们利用order()函数返回元素位置这一特点,可以使用其对数据框进行排序,以鸢尾花数据集为例子

R 复制代码
> iris[order(iris$Sepal.Length),]
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
14           4.3         3.0          1.1         0.1     setosa
9            4.4         2.9          1.4         0.2     setosa
39           4.4         3.0          1.3         0.2     setosa
43           4.4         3.2          1.3         0.2     setosa

同时,order也支持双参数排序

例如

R 复制代码
> iris[order(iris$Sepal.Length,iris$Petal.Length),]
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
14           4.3         3.0          1.1         0.1     setosa
39           4.4         3.0          1.3         0.2     setosa
43           4.4         3.2          1.3         0.2     setosa
9            4.4         2.9          1.4         0.2     setosa
42           4.5         2.3          1.3         0.3     setosa
23           4.6         3.6          1.0         0.2     setosa

先根据Sepal.Length排序,再根据Petal.Length排序

相关推荐
吃好睡好便好5 小时前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
deepin_sir8 小时前
10 - 函数
开发语言·python
z落落8 小时前
C#String字符串
开发语言·c#·php
猫头虎-前端技术8 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
枫叶林FYL9 小时前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
繁华落尽,倾城殇?9 小时前
[C++11] : atomic,nullptr,default/delete,enum class
开发语言·c++·c++11·nullptr·atomic·enum class·default/delete
01_ice9 小时前
C语言数据在内存中的存储
c语言·开发语言
代码村新手9 小时前
C++-二叉搜索树
开发语言·c++
吃好睡好便好11 小时前
创建魔方矩阵和单位矩阵
开发语言·人工智能·学习·线性代数·matlab·矩阵
影寂ldy11 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#