[Rcpp-devel] Most efficient way to apply function over rows of a matrix with Rcpp?

Dirk Eddelbuettel edd at debian.org
Fri Jan 18 04:25:21 CET 2013


Hi Kevin,

First off, congrats regarding RcppRool. Nice to see another package on
CRAN. I had some follow-up questions as to whether you planned to push this
further: the mean at n+1 is really just adding 1/n of the difference between
the newest and the oldest... but getting these things right is hard. Anyway,
I didn't really have time poke around so consider these questions not asked :)

On 17 January 2013 at 18:09, Kevin Ushey wrote:
| Hi guys,
| 
| I'm trying to use Rcpp to implement an 'apply'-type function for matrices,
| whereby I apply a function to each row or column of a matrix. I'm testing it
| here with the 'mean' just to see how well we can do vs. the highly optimized
| rowMeans, colMeans functions, but of course any other function taking a vector
| and returning a scalar might fit here.
| 
| I'm wondering if I can do better. Please see the gist in the link here; you can
| sourceCpp it in R.
| 
| https://gist.github.com/4561281
| 
| I try to limit the amount of copying as much as possible with
| NumericMatrix::Column and NumericMatrix::Row.
| 
| Note that the Rcpp solution over columns is just as fast as colMeans, but over
| rows it's a fair bit slower relative to rowMeans. Is there any way I could
| improve this?

I never measured. I always stopped at the simple sapply/lapply
implementations I showed in the talks/workshops.

One problem is column-wise storage of vectors. For kicks, can you see what
happens when for rowMeans you do a transpose and then compute colMeans ?

| I plan to submit an expanded version of this to the Rcpp gallery so any advice
| is appreciated!

That;s the spirit -- let's grow http://gallery.Rcpp.org which is meant to be
open for contributions.

Cheers,  Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list