我在弄清楚如何将RcppArmadillo colvec作为标准R向量返回时遇到了麻烦。我希望可以通过as<NumericVector>(wrap())
进行类型转换,但最终还是得到R矩阵的对象。这是一些代码来显示我尝试过的内容(部分受this previous question启发):
// [[Rcpp::export]]
List testthis(NumericVector x) {
arma::colvec y = x;
arma::vec z = x;
return List::create(Rcpp::Named("y1")=y,
Rcpp::Named("y2")=wrap(y),
Rcpp::Named("y3")=as<NumericVector>(wrap(y)),
Rcpp::Named("z1")=z,
Rcpp::Named("z2")=arma::trans(z),
Rcpp::Named("z3")=as<NumericVector>(wrap(z))
);
}
如果查看输出,将得到以下所有R矩阵对象。我可以将其转换为R向量吗?
> testthis(c(1:3))
$y1
[,1]
[1,] 1
[2,] 2
[3,] 3
$y2
[,1]
[1,] 1
[2,] 2
[3,] 3
$y3
[,1]
[1,] 1
[2,] 2
[3,] 3
$z1
[,1]
[1,] 1
[2,] 2
[3,] 3
$z2
[,1] [,2] [,3]
[1,] 1 2 3
$z3
[,1]
[1,] 1
[2,] 2
[3,] 3
最佳答案
您只需将dim
属性设置为NULL
,因为矩阵几乎只是带有维属性的常规向量。从C ++方面来看,它看起来像这样:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List testthis(Rcpp::NumericVector x) {
arma::colvec y = x;
arma::vec z = x;
Rcpp::NumericVector tmp = Rcpp::wrap(y);
tmp.attr("dim") = R_NilValue;
Rcpp::List result = Rcpp::List::create(
Rcpp::Named("arma_vec") = y,
Rcpp::Named("R_vec") = tmp);
return result;
}
/*** R
R> testthis(c(1:3))
# $arma_vec
# [,1]
# [1,] 1
# [2,] 2
# [3,] 3
#
# $R_vec
# [1] 1 2 3
R> dim(testthis(c(1:3))[[1]])
#[1] 3 1
R> dim(testthis(c(1:3))[[2]])
# NULL
*/