Skip to content

Instantly share code, notes, and snippets.

@kevinushey
Last active April 14, 2019 06:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinushey/4561281 to your computer and use it in GitHub Desktop.
Save kevinushey/4561281 to your computer and use it in GitHub Desktop.
row, column-wise operations in Rcpp
// the column-wise implementation is just as fast as colMeans,
// but the row-wise operation is not quite as fast as rowMeans.
// can I do better?
#include <Rcpp.h>
using namespace Rcpp;
template <class T>
inline double do_mean( T& x ) {
return mean(x);
}
NumericVector row_means( NumericMatrix& X ) {
int nRows = X.nrow();
NumericVector out = no_init(nRows);
for( int i=0; i < nRows; i++ ) {
NumericMatrix::Row tmp = X(i, _);
out[i] = do_mean( tmp );
}
return out;
}
NumericVector col_means( NumericMatrix& X ) {
int nCols = X.ncol();
NumericVector out = no_init(nCols);
for( int j=0; j < nCols; j++ ) {
NumericMatrix::Column tmp = X(_, j);
out[j] = do_mean( tmp );
}
return out;
}
// [[Rcpp::export]]
NumericVector Mean( NumericMatrix X, int dim ) {
if( dim == 1 ) {
return row_means(X);
} else if( dim == 2 ) {
return col_means(X);
}
}
/*** R
library(rbenchmark)
x <- matrix( rnorm(1E6), ncol=1E3 )
benchmark( replications=5, order=NULL,
apply(x, 1, mean),
Mean(x, 1),
rowMeans(x),
apply(x, 2, mean),
Mean(x, 2),
colMeans(x)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment