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

使用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排序

相关推荐
倔强的石头10611 小时前
Rust实战:使用Axum和SQLx构建高性能RESTful API
开发语言·rust·restful
q***465211 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
柠石榴11 小时前
GO-1 模型本地部署完整教程
开发语言·后端·golang
FAREWELL0007511 小时前
Lua环境的配置 和 Lua的一些简单语法逻辑
开发语言·lua
Blossom.11812 小时前
大模型量化压缩实战:从FP16到INT4的生产级精度保持之路
开发语言·人工智能·python·深度学习·神经网络·目标检测·机器学习
野生工程师12 小时前
【Python爬虫基础-3】数据解析
开发语言·爬虫·python
道199312 小时前
python实现电脑手势识别截图
开发语言·python
奇树谦12 小时前
Qt 自定义菜单栏 / 工具栏按钮 QToolButton + InstantPopup 详细解析
开发语言·数据库·qt
草莓熊Lotso12 小时前
Git 本地操作入门:版本控制基础、跨平台部署与仓库核心流程
开发语言·人工智能·经验分享·git·后端·架构·gitee