rollit_raw {RcppRoll} | R Documentation |
Using this, you can write and wrap in your own C++ function.
rollit_raw(fun, depends = NULL, includes = NULL, inline = TRUE, name = NULL, additional = NULL, ...)
fun |
A character string defining the function call. See examples for usage. |
depends |
Other libraries to link to. Linking is done through Rcpp attributes. |
includes |
Other C++ libraries to include. For example, to include
|
inline |
boolean; mark this function as inline? This may or may not increase execution speed. |
name |
string; a name to internally assign to your generated C++ functions. |
additional |
Other C++ code you want to include; e.g. helper functions.
This code will be inserted as-is above the code in |
... |
Optional arguments passed to |
The signature of fun
is fixed as:
double <name>( NumericVector& x, NumericVector& weights, const int& n, const int& N, const int& ind)
where
X_SUB
is a #define
macro that expands to the sub-vector being rolled over,
X(i)
is a #define
macro that expands to the current element of X_SUB
in a loop being rolled over,
x
is a reference to the entire vector (not just the
sub-vector being rolled over),
weights
are the weights,
n
is the window size,
N
is the number of non-zero weights
passed,
ind
is the current position along vector x
.
Because the variables are being passed by reference, you should not modify them, unless you're prepared for strange behavior. See examples for a potential usage.
## Not run: ## implement a weighted rolling 'sum of squares' fun <- " double out = 0; const double m = mean( X_SUB ); for( int i=0; i < n; i++ ) { out += weights[i] * ( (X(i)-m) * (X(i)-m) ) / (N-1); } return out; " rolling_var <- rollit_raw( fun ) x <- 1:5 rolling_var( x, 5 ) == var(x) ## a (slow-ish) implementation of rolling kurtosis fun <- " double numerator = 0; double denominator = 0; const double m = mean( X_SUB ); for( int i=0; i < n; i++ ) { double tmp = ( X(i) - m ) * ( X(i) - m ); numerator += tmp * tmp; denominator += tmp; } return N * numerator / ( denominator * denominator ); " rolling_kurt <- rollit_raw( fun ) x <- rnorm(100) rolling_kurt(x, 20) ## End(Not run)