Skip to content

Instantly share code, notes, and snippets.

@hadley
Created October 11, 2013 14:23
Show Gist options
  • Save hadley/6935459 to your computer and use it in GitHub Desktop.
Save hadley/6935459 to your computer and use it in GitHub Desktop.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector rowApply0(NumericMatrix& x, const Function& FUN)
{
int n = x.nrow();
NumericVector result = no_init(n);
for (int r = 0; r < n; r++) {
result[r] = as<double>(FUN(x(r, _) ) );
}
return result;
}
// [[Rcpp::export]]
NumericVector rowApply1(NumericMatrix& x, const Function& FUN)
{
int n = x.nrow();
NumericVector result = no_init(n);
for (int r = 0; r < n; r++) {
Language call(FUN, x(r, _)) ;
result[r] = as<double>(call.fast_eval() );
}
return result;
}
// [[Rcpp::export]]
NumericVector rowApply2(NumericMatrix& x, const Function& FUN)
{
int n = x.nrow();
NumericVector result = no_init(n);
Language call(FUN, R_NilValue);
Language::Proxy proxy(call, 1);
for (int r = 0; r < n; r++) {
proxy = x(r, _) ;
result[r] = as<double>(call.fast_eval() );
}
return result;
}
/*** R
library(microbenchmark)
options(digits = 3)
M <- matrix(rnorm(15L), nrow=3L);
identical(rowMeans(M), apply(M, 1L, mean));
identical(rowMeans(M), rowApply0(M, mean));
identical(rowMeans(M), rowApply1(M, mean));
identical(rowMeans(M), rowApply2(M, mean));
microbenchmark(rowMeans(M),
apply(M, 1L, mean),
rowApply0(M, mean),
rowApply1(M, mean),
rowApply2(M, mean))
M <- matrix(rnorm(1500L), nrow=30L);
microbenchmark(rowMeans(M),
apply(M, 1L, mean),
rowApply0(M, mean),
rowApply1(M, mean),
rowApply2(M, mean))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment