Site icon R-bloggers

Using mapply in Rcpp11

[This article was first published on R Enthusiast and R/C++ hero, 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.

mapply is a well known (or perhaps not) function in R. mapply applies a function to extracts from one or more vectors. For example in R:

> mapply( function(x,y, z) x + y + z, 1:4, 4:1, 2)
# [1] 7 7 7 7

Notice how the last argument is recycled as we would expect in R.

I’ve recently updated mapply in Rcpp11 to be as flexible as possible. It handles a variable number of parameters (which the Rcpp version did not do), checks at compile time that it makes sense to apply the function to elements of the input vectors. It also handles primitives instead of vectors, doing recycling.

Here is an example using both vectors and a primitive.

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
NumericVector mapply_example(NumericVector x, NumericVector y, double z){

    auto fun = [](double a, double b, double c){ return a + b + c ;} ;
    return mapply( fun, x, y, z ) ;

}

In this example, the applied function is a lambda, nicely captured with auto because that’s awesome, but we can use a named function previously declared.

double fun(double a, double b, double c){  
    return a + b + c ;
}

// [[Rcpp::export]]
NumericVector mapply_example(NumericVector x, NumericVector y, double z){  
    return mapply( fun, x, y, z ) ;
}

To leave a comment for the author, please follow the link and comment on their blog: R Enthusiast and R/C++ hero.

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.