将arma :: cube子视图转换为NumericVector以使用Sugar

时间:2018-12-21 11:14:21

标签: c++ rcpp armadillo

我将R中的3D数组传递给C ++,并遇到类型转换问题。我们如何使用arma::cube subviews之类的Rcpp的糖函数将NumericVectors从RcppArmadillo转换为which_min以便对其进行操作?

假设您有一个带有一些数字输入的3D立方体Q。我的目标是获取每行i和第三个维度k的列条目最小值的索引。在R语法中,这是which.min(Q[i,,k])

例如i = 1k = 1

cube Q = randu<cube>(3,3,3);
which_min(Q.slice(1).row(1)); // this fails

我认为转换为NumericVector可以解决问题,但此转换失败

which_min(as<NumericVector>(Q.slice(1).row(1))); // conversion failed

我该如何使用它?谢谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您在这里有几个选择:

  1. 您可以仅使用Armadillo函数,即成员函数.index_min()(请参阅Armadillo文档here)。
  2. 您可以使用Rcpp::wrap()"transforms an arbitrary object into a SEXP"可以将arma::cube subviews变成Rcpp::NumericVector并使用糖功能Rcpp::which_min()

最初,我只有第一个选择作为答案,因为这似乎是实现目标的一种更直接的方法,但是我添加了第二个选择(在答案的更新中),因为我现在认为任意转换可能是好奇的一部分。

我将以下C ++代码放在文件so-answer.cpp中:

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

// [[Rcpp::export]]
Rcpp::List index_min_test() {
    arma::cube Q = arma::randu<arma::cube>(3, 3, 3);
    int whichmin = Q.slice(1).row(1).index_min();
    Rcpp::List result = Rcpp::List::create(Rcpp::Named("Q") = Q,
                                           Rcpp::Named("whichmin") = whichmin);
    return result;
}

// [[Rcpp::export]]
Rcpp::List which_min_test() {
    arma::cube Q = arma::randu<arma::cube>(3, 3, 3);
    Rcpp::NumericVector x = Rcpp::wrap(Q.slice(1).row(1));
    int whichmin = Rcpp::which_min(x);
    Rcpp::List result = Rcpp::List::create(Rcpp::Named("Q") = Q,
                                           Rcpp::Named("whichmin") = whichmin);
    return result;
}

我们有一个使用Armadillo的.index_min()的函数,另一个使用Rcpp::wrap()来启用Rcpp::which_min()的函数。

然后,我使用Rcpp::sourceCpp()对其进行编译,使函数可用于R,并演示使用几个不同的种子调用它们:

Rcpp::sourceCpp("so-answer.cpp")
set.seed(1)
arma <- index_min_test()
set.seed(1)
wrap <- which_min_test()
arma$Q[2, , 2]
#> [1] 0.2059746 0.3841037 0.7176185
wrap$Q[2, , 2]
#> [1] 0.2059746 0.3841037 0.7176185
arma$whichmin
#> [1] 0
wrap$whichmin
#> [1] 0
set.seed(2)
arma <- index_min_test()
set.seed(2)
wrap <- which_min_test()
arma$Q[2, , 2]
#> [1] 0.5526741 0.1808201 0.9763985
wrap$Q[2, , 2]
#> [1] 0.5526741 0.1808201 0.9763985
arma$whichmin
#> [1] 1
wrap$whichmin
#> [1] 1
library(microbenchmark)
microbenchmark(arma = index_min_test(), wrap = which_min_test())
#> Unit: microseconds
#>  expr    min      lq     mean  median      uq    max neval cld
#>  arma 12.981 13.7105 15.09386 14.1970 14.9920 62.907   100   a
#>  wrap 13.636 14.3490 15.66753 14.7405 15.5415 64.189   100   a

reprex package(v0.2.1)于2018-12-21创建

相关问题