JCWong
JCWong

Reputation: 1227

Using RcppArmadillo each_col with lambda function?

According to the Armadillo website, you can pass in a lambda function into .each_col, such as

X.each_col( [](vec& a){ a.print(); } );

The following Rcpp seems to have an error though, reporting "Expected Expression"

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
arma::vec colCumSum(const arma::mat& X) {
  return X.each_col( [](const arma::vec& b){ b.cumsum(); } );  
}

Upvotes: 1

Views: 432

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368509

You actually have to tell R to use C++11 in order to have lambda support. The magic line is [[Rcpp::plugins("cpp11")]] which makes it all work:

But once I do that I get issues on the cumsum(). You also had too many const in there.

So here is a simpler version which does work with another lambda from the documentation -- which just prints. I also turned to ivec and imat for consistency:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
arma::ivec colCumSum(arma::imat& X) {
  X.each_col( [](arma::ivec& a){ a.print(); } );
  return X.col(0);
}

/*** R
M <- matrix(1:16, 4, 4)
colCumSum(M)
*/

When you source this, it builds and runs. You will need to work out the lambda use case for the reduction that cumsum() does.

> sourceCpp("/tmp/foo.cpp")

> M <- matrix(1:16, 4, 4)

> colCumSum(M)
        1
        2
        3
        4
        5
        6
        7
        8
         9
        10
        11
        12
        13
        14
        15
        16
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4
> 

Upvotes: 5

Related Questions