Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- N = 3
- M = 5
- P = matrix(rbinom(N*M,10,.5), M)
- ## method 1: eval
- cmd = paste0("order(", paste0("P[,", 1:ncol(P), "]", collapse=","), ",decreasing=T)")
- order_P = eval(parse(text = cmd))
- P2 = P[order_P,] # 你可以全部放到cmd去,無所謂
- ## method 2: quick sort with sort rows
- library(Rcpp)
- library(RcppArmadillo)
- sourceCpp(code = '
- // [[Rcpp::depends(RcppArmadillo)]]
- #include <RcppArmadillo.h>
- using namespace Rcpp;
- using namespace arma;
- inline int compare_vec(const rowvec mat_row, const rowvec pivot_row)
- {
- int v = 0;
- for (uword i = 0; i < mat_row.n_elem; i++)
- {
- if (mat_row(i) < pivot_row(i))
- v = 1;
- else if (mat_row(i) > pivot_row(i))
- v = -1;
- if (v != 0)
- break;
- }
- return v;
- }
- void sortrows_f(mat& M, const int left, const int right)
- {
- if (left < right)
- {
- int i = left, j = right;
- uword mid_loc = (uword) (left+right)/2, pivot_loc = mid_loc;
- rowvec pivot_row = M.row(pivot_loc);
- while (i <= j)
- {
- while (compare_vec(M.row( (uword) i), pivot_row) == 1)
- i++;
- while (compare_vec(M.row( (uword) j), pivot_row) == -1)
- j--;
- if (i <= j)
- {
- M.swap_rows((uword) i, (uword) j);
- i++;
- j--;
- }
- }
- if (j > 0)
- sortrows_f(M, left, j);
- if (i < (int) M.n_rows - 1)
- sortrows_f(M, i, right);
- }
- }
- // [[Rcpp::export]]
- mat sortbyrow(mat M, bool decreasing = true){
- sortrows_f(M, (int) 0, (int) M.n_rows-1);
- if (decreasing)
- return flipud(M);
- return M;
- }')
- P3 = sortbyrow(P)
- all.equal(P2, P3)
Advertisement
Add Comment
Please, Sign In to add comment