使用带有lambda函数的RcppArmadillo each_col?

JCW*_*ong 1 r rcpp

根据Armadillo网站,您可以将lambda函数传入.each_col,例如

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

以下Rcpp似乎有错误,报告“预期表达式”

#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(); } );  
}
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 5

实际上,您必须告诉R使用C ++ 11才能获得lambda支持。魔术线[[Rcpp::plugins("cpp11")]]使所有这些工作:

但是一旦这样,我就会遇到问题cumsum()。您const那里也有太多东西。

因此,这里是一家简单的版本的工作与另一个lambda从文档-这只是打印。我也转向ivecimat一致性:

#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)
*/
Run Code Online (Sandbox Code Playgroud)

当您获取此资源时,它将生成并运行。您将需要计算出lambda用例,以实现此目的cumsum()

> 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
> 
Run Code Online (Sandbox Code Playgroud)