Calling R Functions from C++

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

At its very essence, Rcpp permits easy access to native R objects at the C++ level. R objects can be

  • simple vectors, list or matrices;
  • compound data structures created from these;
  • objects of S3, S4 or Reference Class vintage; or
  • language objects as for example environments.

Accessing a function object is no different. And calling a function can be very useful. Maybe to pick up parameter initializations, maybe to access a custom data summary that would be tedious to recode, or maybe even calling a plotting routine. We already have examples for just about all of these use case in the Rcpp examples or unit tests shipping with the package.

So here were a just providing a simple example of calling a summary function, namely the Tukey fivenum().

But before we proceed, a warning. Calling a function is simple and tempting. It is also slow as there are overheads involved. And calling it repeatedly from inside your C++ code, possibly buried within several loops, is outright silly. This has to be slower than equivalent C++ code, and even slower than just the R code (because of the marshalling of data). Do it when it makes sense, and not simply because it is available.

set.seed(42)
x <- rnorm(1e5)
fivenum(x)


[1] -4.043276 -0.682384 -0.002066  0.673325  4.328091

Now via this C++ code:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector callFunction(NumericVector x, Function f) {
    NumericVector res = f(x);
    return res;
}

And unsurprisingly, calling the same function on the same data gets the same result:

callFunction(x, fivenum)


[1] -4.043276 -0.682384 -0.002066  0.673325  4.328091

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)