Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return RcppArmadillo vector as R vector

Tags:

r

rcpp

I having trouble figuring out how to return an RcppArmadillo colvec as a standard R vector. I was hoping I could typecast through as<NumericVector>(wrap()) but I still end up with objects that are R matrices. Here's a bit of code to show what I've 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 output I get the following which are all R matrix objects. Can I cast 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
like image 707
ekstroem Avatar asked Sep 15 '15 07:09

ekstroem


1 Answers

You can just set the dim attribute to NULL, since matrices are pretty much just regular vectors with a dimensional 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

*/
like image 112
nrussell Avatar answered Oct 04 '22 17:10

nrussell