x <- matrix(1:16, nrow=4)
cvApply <- rcpp_apply_generator("return mean(x) / sd(x);")
squaredSumApply <- rcpp_apply_generator("
double out = 0;
for( int i=0; i < x.size(); i++ ) {
out += x[i];
}
out = out*out;
return out;
")
cvApply(x, 2)
apply(x, 2, mean) / apply(x, 2, sd)
if( require(microbenchmark) ) {
f <- function(x) { mean(x) / sd(x) }
microbenchmark( cvApply(x, 2), apply(x, 2, f) )
}
## example with bool
anyBig <- rcpp_apply_generator( returnType="bool", '
return is_true( any( x > 10 ) );
')
anyBig(x, 2)
anyBig(x, 1)
## example with boost's gcd. silly but demonstrative.
## intended to be applied to matrices with 2 rows and n columns
gcdApply <- rcpp_apply_generator(
includes="<boost/math/common_factor.hpp>",
fun='
NumericVector tmp1 = x;
std::vector<int> tmp = as< std::vector< int > >(tmp1);
return boost::math::gcd( tmp[0], tmp[1] );
')
M <- matrix( c(4, 6, 20, 25, 10, 100), nrow=2 )
gcdApply(M, 2)
Run the code above in your browser using DataLab