在 Rcpp (Armadillo) 函数中使用数字序列作为默认参数

Ber*_*riJ 4 c++ r rcpp rcpparmadillo

我需要这个来完成一个更大的项目,但我认为这个最小的代表可以最好地解释它。我在 R 中有以下函数:

test <- function(x = 2^(1:9)) {
    x
}
test()
#> [1]   2   4   8  16  32  64 128 256 512
Run Code Online (Sandbox Code Playgroud)

这工作正常。但是,我想使用 Rcpp Armadillo 将其转换为 Rcpp。我使用以下 test.cpp 文件尝试了此操作:

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace arma;

// [[Rcpp::export]]
vec test(const vec &lambda = arma::exp2(arma::linspace(1, 9, 9)))
{
    return lambda;
}
Run Code Online (Sandbox Code Playgroud)

但是使用编译它Rcpp::sourceCpp("functions/test.cpp")会产生一个警告:

警告消息:无法解析函数 test 的参数 lambda 的 C++ 默认值 'arma::exp2(arma::linspace(1, 9, 9))'

并且默认参数不起作用(调用test())。

预先非常感谢。

Dir*_*tel 5

你不能“根据我们这里的合同”这样做,因为通过导出签名使其成为 R 可以看到并可以调用的东西,它必须符合.Call()R API 中 a 的签名,这是一个 C 函数,其中每个参数是A SEXP

因此接口上不允许使用 C++ 表达式。您可以将该逻辑移入内部作为第二最佳选择。

修改代码

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

// [[Rcpp::export]]
arma::vec testCpp(const int s, const int e, const int n) {
    arma::vec lambda = arma::exp2(arma::linspace(s, e, n));
    return lambda;
}

/*** R
testCpp(1,9, 9)
*/
Run Code Online (Sandbox Code Playgroud)

输出

> Rcpp::sourceCpp("~/git/stackoverflow/65357225/answer.cpp")

> testCpp(1,9, 9)
      [,1]
 [1,]    2
 [2,]    4
 [3,]    8
 [4,]   16
 [5,]   32
 [6,]   64
 [7,]  128
 [8,]  256
 [9,]  512
> 
Run Code Online (Sandbox Code Playgroud)