rcpp_apply_generator: Rcpp Apply Generator

Description Usage Arguments Examples

View source: R/rcpp_apply_generator.R

Description

Use this function as a generator for your own apply functions; that is, functions you would like to apply over rows or columns of a matrix.

Usage

1
2
3
4
5
rcpp_apply_generator(fun, includes = NULL, depends = NULL, inline = TRUE,
  returnType = "double", name = NULL, file = NULL, additional = NULL)

Rcpp_apply_generator(fun, includes = NULL, depends = NULL, inline = TRUE,
  returnType = "double", name = NULL, file = NULL, additional = NULL)

Arguments

fun

A character string defining the C++ function. It must be in terms of a variable x, and it must return a double. x is a reference to the current row/column being iterated over.

includes

Other C++ libraries to include. For example, to include boost/math.hpp, you could pass c("<boost/math.hpp>"). Rcpp is included by default, unless RcppArmadillo is included as well (since Rcpp is included as part of the RcppArmadillo include)

depends

Other libraries to link to. Linking is done through Rcpp attributes.

inline

boolean; mark this function as inline? This may or may not increase execution speed.

returnType

The return type of your function; must be a scalar that is wrappable by Rcpp. Currently, the supported choices are double, int, and bool.

name

An internal name for the function.

file

A location to output the file. Defaults to a temporary file as generated by tempfile().

additional

Other C++ code you want to include; e.g. helper functions. This code will be inserted as-is above the code in fun.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
## Not run: 
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( returnType="int",
  includes="<boost/math/common_factor.hpp>",
  fun='
  return boost::math::gcd( (int)x[0], (int)x[1] );
  ')
M <- matrix( c(4, 6, 20, 25, 10, 100), nrow=2 )
gcdApply(M, 2)

## End(Not run)

Kmisc documentation built on May 29, 2017, 1:43 p.m.