RaggedArrayCpp: Writing user-supplied C++ functions for 'sapply*C' and...

Description Details Gory Details See Also

Description

This page describes how to write user-supplied C++ functions for use by RaggedArray objects. The easiest way is to follow and extend the examples provided in the userFun.cpp file. Also see the unit tests, contained in the ./inst/tests directory.

Details

Users can provide R functions to the sapply and mapply methods of RaggedArrayClass objects, but R functions require non-trivial overhead to access from C++. Alternately, users can write their own C++ functions. In order for a RaggedArrayClass object to access user-supplied C++ functions, a second wrapper function must return an external pointer to the C++ function.

Most users should simply modify and extend the examples provided in the userFun.cpp file. A call to sourceCpp("userFun.cpp") will automatically compile and link the user functions. Compilation only occurs as needed, so extra calls to sourceCpp() incur no cost, and can be safely added to R scripts. Note that this sourceCpp() mechanism is not appropriate for packages that extend RaggedArray.

Gory Details

To use sapplyC*, two functions are required. First, the desired computation is conducted by a worker function with signature void workerFun(arma::vec& x). This function should assign its results to x (modifying x in-place). A second function userFun returns an appropriately-typed XPtr to workerFun. userFun is exported via Rcpp attributes and passed by the user to sapplyC or sapplyAllocC. Internally, sapply*C calls this function, dereferences the resulting pointer, and calls the appropriate workerFun on each vector in RaggedArray.

The example code in the userFun.cpp file includes two typedefs for use with sapplyC and mapplyC, respectively:

The signatures of the exported C++ functions userFunSapply userFunMapply (for use the respective *applyC methods) are then:

A full example for use with sapplyC thus includes 2 C++ functions and an R call. The C++ functions are:

1
2
3
4
5
6
7
8
9
// worker function, modify x in-place
void workerMult(arma::vec& x) {
   x = 10*x;
}
// return external pointer to workerFun, export with Attributes
// [[Rcpp::export]]
XPtr<funcPtr> userFunSapplyMult() {
   return(XPtr<funcPtr>(new funcPtr(&workerMult)));
}

The final R call is: object$sapplyC(userFunSapplyMult).

See Also

sourceCpp sapply mapply

Other RaggedArray.Docs: RaggedArray, RaggedArrayClass


helmingstay/RaggedArray documentation built on May 17, 2019, 3:38 p.m.