R語言:排序的應用操作

工作中遇到過許多看起來挺復雜的數據篩選,本質上都可以用排序解決,這裡以R自帶的mtcar數據集為例做一個記錄。

首先簡單介紹一下mtcar數據集,mtcar(Motor Trend Car Road Tests)是一個32行11列的數據集,記錄瞭32種汽車的11種性能,具體數據如下:

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

3.冒泡排序

# bubble sort
bubbleSort = 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 sort
quickSort = 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 sort
insertSort = 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 sort
shellSort = 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 sort
selectSort = 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 sort
adjustHeap = 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 sort
combine = 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)
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀:

    None Found