你有几个选择:
- 您可以为此使用 Armadillo 函数,成员函数
.index_min()(请参阅 Armadillo 文档 here)。
- 您可以使用
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 日创建