Note that there are some explanatory texts on larger screens.

plurals
  1. POwhich(x, arr.ind=T) in RCPP
    primarykey
    data
    text
    <p>I couldn't find the cool <code>which(x,arr.ind=T)</code> feature in Rcpp or RcppArmadillo. So I decided to quickly code that up on my own.</p> <pre><code>// [[Rcpp::export]] arma::umat whicha(arma::mat matrix, int what ){ arma::uvec outp1; int n = matrix.n_rows; outp1 = find(matrix==what); int nf = outp1.n_elem; arma::mat out(nf,2); arma::vec foo; arma::uvec foo2; foo = arma::conv_to&lt;arma::colvec&gt;::from(outp1) +1; foo2 = arma::conv_to&lt;arma::uvec&gt;::from(foo); for(int i=0; i&lt;nf; i++){ out(i,0) = ( foo2(i) %n); out(i,1) = ceil(foo(i) / n ); if(out(i,0)==0) { out(i,0)=n; } } return(arma::conv_to&lt;arma::umat&gt;::from(out)); } </code></pre> <p>The code seems quite inefficient, but <code>microbenchmark</code> reveals that it can be faster than R's <code>which</code> function.</p> <p>Question: Can I further change this function to actually exactly reproduce R's <code>which</code> function, i.e. pass <code>MATRIX == something</code> to it? Right now I need a second argument for that. I just like to have this for convenience.</p> <hr> <p>Update: fixed a bug - needed ceil instead of floor</p> <p>How to check:</p> <pre><code>ma=floor(abs(rnorm(100,0,6))) testf=function(k) {all(which(ma==k,arr.ind=T) == whicha(ma,k))} ; sapply(1:10,testf) </code></pre> <p>Benchmark:</p> <pre><code>&gt; microbenchmark(which(ma==k,arr.ind=T) , whicha(ma,k)) Unit: microseconds expr min lq median uq max neval which(ma == k, arr.ind = T) 10.264 11.170 11.774 12.377 51.317 100 whicha(ma, k) 3.623 4.227 4.830 5.133 36.224 100 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload