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

使用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 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian5 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡5 天前
简单工厂模式
开发语言·算法·c#