0

In short: Is there an rcpp or rcpparmadillo function that calculates rank with ties = "random"?

Long Summary: I am trying to convert a program written in R to a combination of C++, Rcpp and Rcpp Armadillo. The R program makes use of the R function Rank on a numeric vector called "fitness.old". Some example calls are the following:

sort(pop[rank(fitness.old,ties.method="random")==1,])

sample(v,1,prob=rank(-fitness.old[v])

I have spent lots of time trying to find equivalent functions or code for Rank in Rcpp Armadillo or Rcpp but have had no luck. This post

Rcpp sugar for rank function

was the closest I could find to a possible solution. However, I want rank(x, ties = "random") NOT rank(x, ties = "first"). Does anyone know how I can accomplish this?

1 Answers1

0

Rcpp Armadillo solution:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace arma;


// [[Rcpp::export]]
umat arma_rank(vec x) {
  umat d(x.n_rows,x.n_rows,fill::eye);
  umat res=index_max(d.rows(sort_index(x)))+1;
  return(res);
}

/*** R
x<-rnorm(100)
all(drop(arma_rank(x))==rank(x))
*/

> Rcpp::sourceCpp("arma_rank.cpp")

> x<-rnorm(100)

> all(drop(arma_rank(x))==rank(x))
[1] TRUE
> 

much slower than rank:

> microbenchmark(arma_rank(x))
Unit: microseconds
         expr    min      lq     mean median     uq     max neval
 arma_rank(x) 78.761 79.3555 88.44151 81.795 84.788 708.275   100
> microbenchmark(rank(x))
Unit: microseconds
    expr   min    lq     mean median    uq     max neval
 rank(x) 7.339 7.544 12.63538 7.7285 8.446 428.081   100
> 
Nick Nassuphis
  • 257
  • 2
  • 6