rollit {RcppRoll} | R Documentation |
Using this interface, you can define a function that you would like to
be called on each sub-vector you are rolling over. The generated code is
compiled and exposed via sourceCpp
.
rollit(fun = "x", vector = FALSE, const_vars = NULL, combine = "+", final_trans = NULL, includes = NULL, depends = NULL, inline = TRUE, name = NULL, ...)
fun |
A character string defining the function call. The function must be in
terms of |
vector |
boolean; if |
const_vars |
Constant variables that will live within
the sourced C++ function. Format is a named |
combine |
character; typically one of |
final_trans |
A final transformation to perform after either 'rolling'
over each element in the vector |
includes |
Other C++ libraries to include. For example, to include
|
depends |
Other libraries to link to. Linking is done through Rcpp attributes. |
inline |
boolean; mark the function generated as |
name |
string; a name to internally assign to your generated C++ functions. |
... |
Additional arguments passed to |
By default, we include <RcppArmadillo.h>
in each file; however, you can
include your own libraries with the includes
call.
A wrapper R function that calls compiled C++ files, as generated through
sourceCpp
. See rollit_example
for more information on the
functions generated by rollit
.
All functions generated use Rcpp's NumericVector
and
NumericMatrix
to interface with R vectors and matrices.
Elements within these vectors are
translated as double
s so any function that receives a double
will work fine.
If you want to just write your own C++ function to wrap into a 'rolling'
interface, see rollit_raw
.
rollit_example
for an example of the function signature
for functions generated with rollit
,
sourceCpp
for information on how Rcpp
compiles your functions, get_rollit_source
for
inspection of the generated C++ code, and rollit_raw
for
wrapping in your own C++ code.
## Not run: x <- matrix(1:16, nrow=4) ## the squared rolling sum -- we square the sum of our rolled results rolling_sqsum <- rollit( final_trans="x*x" ) rolling_sqsum( x, 4 ) rolling_sqsum( x, 4, by.column=FALSE ) cbind( as.vector(rolling_sqsum(x, 4)), apply(x, 2, function(x) { sum(x)^2 } ) ) ## implement your own variance function ## we can use the sugar function 'mean' to get ## the mean of x const_vars <- list(m = "mean(x)") var_fun <- "( (x-m) * (x-m) )/(N-1)" rolling_var <- rollit( var_fun, const_vars=const_vars ) x <- c(1, 5, 10, 15) cbind( rolling_var(x, 2), roll_var(x, 2) ) ## use a function from cmath rolling_log10 <- rollit( "log10(x)" ) rolling_log10( 10^(1:5), 2 ) ## rolling product rolling_prod <- rollit( combine="*" ) rolling_prod( 1:10, 2 ) ## using weights to specify something like a 'by' argument rolling_prod( 1:10, 3, weights=c(1,0,1) ) ## a benchmark if( require("microbenchmark") && require("zoo") ) { x <- rnorm(1E4) microbenchmark( rolling_var(x, 100), roll_var(x, 100), rollapply(x, 100, var), times=10 ) } ## End(Not run)