celestialgod

sort rows

Aug 26th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.74 KB | None | 0 0
  1. N = 3
  2. M = 5
  3. P = matrix(rbinom(N*M,10,.5), M)
  4.  
  5. ## method 1: eval
  6. cmd = paste0("order(", paste0("P[,", 1:ncol(P), "]", collapse=","), ",decreasing=T)")
  7. order_P = eval(parse(text = cmd))
  8. P2 = P[order_P,] # 你可以全部放到cmd去,無所謂
  9.  
  10. ## method 2: quick sort with sort rows
  11. library(Rcpp)
  12. library(RcppArmadillo)
  13.  
  14. sourceCpp(code = '
  15. // [[Rcpp::depends(RcppArmadillo)]]
  16. #include <RcppArmadillo.h>
  17. using namespace Rcpp;
  18. using namespace arma;
  19.  
  20. inline int compare_vec(const rowvec mat_row, const rowvec pivot_row)
  21. {
  22.    int v = 0;
  23.    for (uword i = 0; i < mat_row.n_elem; i++)
  24.    {
  25.        if (mat_row(i) < pivot_row(i))
  26.            v = 1;
  27.        else if (mat_row(i) > pivot_row(i))
  28.            v = -1;
  29.        if (v != 0)
  30.            break;
  31.    }
  32.    return v;
  33. }
  34.  
  35. void sortrows_f(mat& M, const int left, const int right)
  36. {
  37.    if (left < right)
  38.    {
  39.        int i = left, j = right;
  40.        uword mid_loc = (uword) (left+right)/2, pivot_loc = mid_loc;
  41.        rowvec pivot_row = M.row(pivot_loc);
  42.        while (i <= j)
  43.        {
  44.            while (compare_vec(M.row( (uword) i), pivot_row) == 1)
  45.                i++;
  46.            while (compare_vec(M.row( (uword) j), pivot_row) == -1)
  47.                j--;
  48.            if (i <= j)
  49.            {
  50.                M.swap_rows((uword) i, (uword) j);
  51.                i++;
  52.                j--;
  53.            }
  54.        }
  55.        if (j > 0)
  56.            sortrows_f(M, left, j);
  57.        if (i < (int) M.n_rows - 1)
  58.            sortrows_f(M, i, right);
  59.    }
  60. }
  61.  
  62. // [[Rcpp::export]]
  63. mat sortbyrow(mat M, bool decreasing = true){
  64.  sortrows_f(M, (int) 0, (int) M.n_rows-1);
  65.  if (decreasing)
  66.    return flipud(M);
  67.  return M;
  68. }')
  69. P3 = sortbyrow(P)
  70. all.equal(P2, P3)
Advertisement
Add Comment
Please, Sign In to add comment