Returns the RcppArmadillo vector as a vector R

I find it difficult to figure out how to return RcppArmadillo colvec as a standard R-vector. I was hoping I could type in as<NumericVector>(wrap() , but I still get objects with R matrices. Here is some code to show what I tried (partially inspired by 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)) ); } 

and if I look at the result, I get the following: all R-matrix objects. Can I attribute it to R-vectors?

 > 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 
+6
source share
3 answers

You can simply set the dim attribute to NULL , since matrices are pretty simple regular vectors with a dimension attribute. From the C ++ side, it looks like this:

 #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 */ 
+9
source

This is a "feature." At some point, very early, we decided to keep the dimensions, so the vectors always return in the form of matrices with one row or column. Since this API was installed quite a while ago, it is now difficult to change, since we will break the existing code.

Kudos to verify all of the above options. Here is another way to help by going through std::vector<double> :

 R> cppFunction("std::vector<double> foo(arma::vec v) { + return as<std::vector<double> >(wrap(v)); }", + depends="RcppArmadillo") R> foo(c(5.5,6.6,7.42)) [1] 5.50 6.60 7.42 R> 

It might be more efficient to simply split the size on the R side.

+5
source

This is an old question, but it still appears in the first lines when searching for an object, so I would like to share another option that is possible from version 0.7.960.1.0. Insert the appropriate #define before #include and voilà:

 #define RCPP_ARMADILLO_RETURN_COLVEC_AS_VECTOR #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::vec testthis(arma::vec x) { return x+1; } /*** R testthis(1:3) */ > testthis(1:3) [1] 2 3 4 

You can replace COLVEC with #define with ROWVEC or ANYVEC if necessary.

+1
source

All Articles