cppFunction: Define an R Function with a C++ Implementation

Description Usage Arguments Details Value Note See Also Examples

Description

Dynamically define an R function with C++ source code. Compiles and links a shared library with bindings to the C++ function then defines an R function that uses .Call to invoke the library.

Usage

1
2
3
cppFunction(code, depends = character(), includes = character(), 
            env = parent.frame(), rebuild = FALSE, 
            showOutput = verbose, verbose = getOption("verbose"))

Arguments

code

Source code for the function definition.

depends

Character vector of packages that the compilation depends on. Each package listed will first be queried for an inline plugin to determine header files to include. If no plugin is defined for the package then a header file based the package's name (e.g. PkgName.hpp) will be included.

includes

Character vector of user includes (inserted after the includes provided by depends).

env

The environment in which to define the R function. May be NULL in which case the defined function can be obtained from the return value of cppFunction.

rebuild

Force a rebuild of the shared library.

showOutput

TRUE to print R CMD SHLIB output to the console.

verbose

TRUE to print detailed information about generated code to the console.

Details

Functions defined using cppFunction must have return types that are compatible with Rcpp::wrap and parameter types that are compatible with Rcpp::as.

The shared library will not be rebuilt if the underlying code has not changed since the last compilation.

Value

An R function that uses .Call to invoke the underlying C++ function.

Note

You can also define R functions with C++ implementations using the sourceCpp function, which allows you to separate the C++ code into it's own source file. For many use cases this is an easier and more maintainable approach.

See Also

sourceCpp, evalCpp

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
## Not run: 

cppFunction(
    'int fibonacci(const int x) {
        if (x == 0) return(0); 
        if (x == 1) return(1);
        return (fibonacci(x - 1)) + fibonacci(x - 2);
    }')

cppFunction(depends = "RcppArmadillo",
    'List fastLm(NumericVector yr, NumericMatrix Xr) {
        
        int n = Xr.nrow(), k = Xr.ncol();
        
        arma::mat X(Xr.begin(), n, k, false); 
        arma::colvec y(yr.begin(), yr.size(), false);
        
        arma::colvec coef = arma::solve(X, y);
        arma::colvec resid = y - X*coef;
        
        double sig2 = arma::as_scalar(arma::trans(resid)*resid/(n-k) );
        arma::colvec stderrest = arma::sqrt(
            sig2 * arma::diagvec(arma::inv(arma::trans(X)*X)));
        
        return List::create(Named("coefficients") = coef,
            Named("stderr")       = stderrest
        );
    }')

## End(Not run)

jjallaire/Rcpp documentation built on May 19, 2019, 11:37 a.m.