Using mapply in Rcpp11

May 22, 2014

(This article was first published on R Enthusiast and R/C++ hero, and kindly contributed to R-bloggers)

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

plotly webpage

dominolab webpage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training




CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

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)