R语言:排序的应用操作

时间:2021-05-20

工作中遇到过许多看起来挺复杂的数据筛选,本质上都可以用排序解决,这里以R自带的mtcar数据集为例做一个记录。

首先简单介绍一下mtcar数据集,mtcar(Motor Trend Car Road Tests)是一个32行11列的数据集,记录了32种汽车的11种性能,具体数据如下:

> mtcars mpg cyl disp hp drat wt qsec vs am gear carbMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2

假如我们想挑一款比较省油的车,也就是选一款mpg(每加仑公里数)较高的车。如果只要一个备选,自然可以使用which.max函数:

> mtcars[which.max(mtcars$mpg), ] mpg cyl disp hp drat wt qsec vs am gear carbToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.9 1 1 4 1

如果想要多个备选呢?例如2个备选。我们可以将mtcars按mpg从大到小排序,然后列出前两个:

> db_use <- mtcars[order(mtcars$mpg, decreasing = T), ] > db_use mpg cyl disp hp drat wt qsec vs am gear carbToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2

前两名是:

> db_use[1:2, ] mpg cyl disp hp drat wt qsec vs am gear carbToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1

如果取前3名呢?我们注意到存在并列第3的情况,所以说直接取前3行就不合适了。这样我们可以新设一列表示mpg的排名(rank),然后取排名小于等于3的数据。但是rank函数是从小到大排序的,我们这里要从大到小排序,需要做一个简单的变换:

> db_use$rank <- nrow(db_use) - rank(db_use$mpg, ties.method = 'max') + 1> db_use mpg cyl disp hp drat wt qsec vs am gear carb rankToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 1Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 2Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 3Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 3Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 5Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 6

选取前3名:

> db_use[which(db_use$rank<= 3), ] mpg cyl disp hp drat wt qsec vs am gear carb rankToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 1Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 2Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 3Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 3

下面增加一下难度。现在我们挑选出来的车都是4缸的,即cyl(气缸数)为4。我们想在不同气缸数的车中都挑一些省油的车做备选,比方说在不同气缸数的车中挑出各自前3款最省油的车。

同样,我们需要构造一个新变量表示mpg的排名,只不过这个排名是一个分组排名,即以气缸数分组,在气缸数相同的车中分别排名。

首先,我们将数据按气缸数分组排好:

> library(dplyr)> db_use <- mtcars> db_use$name <- rownames(db_use)> db_use <- arrange(db_use, cyl, desc(mpg))> db_use mpg cyl disp hp drat wt qsec vs am gear carb name1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla2 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 1283 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic4 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa5 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Fiat X1-96 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Porsche 914-2

然后列出各组的组内rank:

> rank_group <- aggregate(mpg~cyl, db_use, rank, ties.method = 'max')> db_use$rank_increase <- unlist(rank_group$mpg)> db_use mpg cyl disp hp drat wt qsec vs am gear carb name rank_increase1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla 112 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128 103 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic 94 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa 95 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Fiat X1-9 76 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Porsche 914-2 6

接着,算出每组各包含多少数据:

> num_all <- aggregate(mpg~cyl, db_use, length)> db_use$num_all <- rep(num_all$mpg, num_all$mpg)> db_use mpg cyl disp hp drat wt qsec vs am gear carb name rank_increase num_all1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla 11 112 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128 10 113 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic 9 114 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa 9 115 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Fiat X1-9 7 116 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Porsche 914-2 6 11

最后二者相减得出各组的组内从大到小排名,选取排名小于等于3的汽车::

> db_use$rank_decrease <- db_use$num_all - db_use$rank_increase + 1> db_use[which(db_use$rank_decrease <= 3), ] mpg cyl disp hp drat wt qsec vs am gear carb name rank_increase num_all rank_decrease1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla 11 11 12 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128 10 11 23 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Honda Civic 9 11 34 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Lotus Europa 9 11 312 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive 7 7 113 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 6 7 214 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag 6 7 219 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Pontiac Firebird 14 14 120 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Hornet Sportabout 13 14 221 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SL 12 14 3

有时候我们不会挑选具体前3名还是前5名的数据,会是取一个百分比,比方说在各组内挑选前20%最省油的车辆,这个需求利用前边的几个中间变量新设一个百分比变量就能轻松实现:

> db_use[which(db_use$Percent <= 0.2), ] mpg cyl disp hp drat wt qsec vs am gear carb name rank_increase num_all rank_decrease Percent1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla 11 11 1 0.090909092 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Fiat 128 10 11 2 0.1818181812 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive 7 7 1 0.1428571419 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Pontiac Firebird 14 14 1 0.0714285720 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Hornet Sportabout 13 14 2 0.14285714

补充:R语言中的排序算法

最近用R语言比较多,所以这次再一次整理一下R语言中的排序算法,本篇文章主要以代码实现为主,原理不在此赘述了。

文中如有不正确的地方,欢迎大家批评指正。

1.测试数据

<span style="font-size:18px;"># 测试数组vector = c(5,34,65,36,67,3,6,43,69,59,25,785,10,11,14)vector## [1] 5 34 65 36 67 3 6 43 69 59 25 785 10 11 14</span>

2.R语言中自带的排序函数

在R中,跟排序有关的函数主要有三个:sort(),rank(),order()。其中sort(x)是对向量x进行排序,rank()是求秩的函数,它的返回值是这个向量中对应元素的“排名”,order()的返回值是对应“排名”的元素所在向量中的位置。

sort(vector)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785order(vector)## [1] 6 1 7 13 14 15 11 2 4 8 10 3 5 9 12rank(vector)## [1] 2 8 12 9 13 1 3 10 14 11 7 15 4 5 6

3.冒泡排序

# bubble sortbubbleSort = function(vector) { n = length(vector) for (i in 1:(n-1)) { for (j in (i+1):n) { if(vector[i]>=vector[j]){ temp = vector[i] vector[i] = vector[j] vector[j] = temp } } } return(vector)}bubbleSort(vector)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785

4.快速排序

# quick sortquickSort = function(vector, small, big) { left = small right = big if (left >= right) { return(vector) }else{ markValue = vector[left] while (left < right) { while (left < right && vector[right] >= markValue) { right = right - 1 } vector[left] = vector[right] while (left < right && vector[left] <= markValue) { left = left + 1 } vector[right] = vector[left] } vector[left] = markValue vector = quickSort(vector, small, left - 1) vector = quickSort(vector, right + 1, big) return(vector) }}quickSort(vector,1,15)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785

5.插入排序

# insert sortinsertSort = function(vector){ n = length(vector) for(i in 2:n){ markValue = vector[i] j=i-1 while(j>0){ if(vector[j]>markValue){ vector[j+1] = vector[j] vector[j] = markValue } j=j-1 } } return(vector)}insertSort(vector)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785

6.希尔排序

# shell sortshellSort = function(vector){ n = length(vector) separate = floor(n/2) while(separate>0){ for(i in 1:separate){ j = i+separate while(j<=n){ m= j- separate markVlaue = vector[j] while(m>0){ if(vector[m]>markVlaue){ vector[m+separate] = vector[m] vector[m] = markVlaue } m = m-separate } j = j+separate } } separate = floor(separate/2) } return(vector)}shellSort(vector)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785

7.选择排序

# select sortselectSort = function(vector){ n = length(vector) for(i in 1:(n-1)){ minIndex = i for(j in (i+1):n){ if(vector[minIndex]>vector[j]){ minIndex = j } } temp = vector[i] vector[i] = vector[minIndex] vector[minIndex] = temp } return(vector)}selectSort(vector)## [1] 3 5 6 10 11 14 25 34 36 43 59 65 67 69 785

8.堆排序

# heap sortadjustHeap = function(vector,k,n){ left = 2*k right = 2*k+1 max = k if(k<=n/2){ if(left<=n&&vector[left]>=vector[max]){ max = left } if(right<=n&&vector[right]>=vector[max]){ max = right } if(max!=k){ temp = vector[k] vector[k] = vector[max] vector[max] = temp vector = adjustHeap(vector,max,n) } } return(vector)}createHeap = function(vector,n){ for(i in (n/2):1){ vector = adjustHeap(vector,i,n) } return(vector)}heapSort = function(vector){ n = length(vector) vector = createHeap(vector,n) for(i in 1:n){ temp = vector[n-i+1] vector[n-i+1] = vector[1] vector[1] = temp vector = adjustHeap(vector,1,n-i) } return(vector)}

9.归并排序

# merge sortcombine = function(leftSet,rightSet){ m = 1 n = 1 vectorTemp = c() while (m<=length(leftSet)&&n<=length(rightSet)) { if(leftSet[m]<=rightSet[n]){ vectorTemp = append(vectorTemp,leftSet[m]) m = m+1 }else{ vectorTemp = append(vectorTemp,rightSet[n]) n = n+1 } } if(m>length(leftSet)&&n==length(rightSet)){ vectorTemp = append(vectorTemp,rightSet[n:length(rightSet)]) }else if(m==length(leftSet)&&n>length(rightSet)){ vectorTemp = append(vectorTemp,leftSet[m:length(leftSet)]) } return(vectorTemp)}mergeSort = function(vector){ size = length(vector) if(size==1){ return(vector) } cut = ceiling(size/2) leftSet = mergeSort(vector[1:cut]) rightSet = mergeSort(vector[(cut+1):size]) vector = combine(leftSet,rightSet) return(vector)}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章