Question

I am trying to use Rcpp lapply function with functions with multiple arguments.

In R the same can be done with the following code.

lapply(y,FUN=function(x)corr(x[,2:ncol(x)],x[,1]))

where corr is a function that takes two arguments.

Can anybody give an example code in Rcpp for the above situation?

Was it helpful?

Solution

If I understand what you want correctly, based on your latest comments, what you need is mapply rather than sapply, e.g. :

> mapply( function(a, b) a == b, 1:9, 9:1 )
# [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

Rcpp has mapply (for two or 3 arguments)

#include <Rcpp.h>
using namespace Rcpp ;

struct Compare : public std::binary_function<int,int,bool> {   
    bool operator() (int a, int b) const {
        return (a==b);
    } 
};

// [[Rcpp::export]]
LogicalVector test( NumericVector x, NumericVector y){
    return mapply( x, y, Compare() ) ;
}

which I would tend to write like this with C++11 lambdas.

// [[Rcpp::export]]
LogicalVector test( NumericVector x, NumericVector y){
    return mapply( x, y, [](double a, double b){ 
            return a == b ;
    } ) ;
}

Or even using the std::equal_to<double> class:

// [[Rcpp::export]]
LogicalVector test( NumericVector x, NumericVector y){
    return mapply( x, y, std::equal_to<double>() ) ;
}

However, for such trivial functions, you should be using sugar:

// [[Rcpp::export]]
LogicalVector test( NumericVector x, NumericVector y){
    return x == y ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top