Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize a NumericVector?

Tags:

r

rcpp

How can I resize in Rcpp a NumericVector?

When I use the push_back function for this, the Program slows down. But there are no .resize() or .reserve() functions. (When I have already a NumericVector with the desired size, I can use the copy-constructor to get the correct size of the NumericVector. This is in such a case much faster than usage of push_back)

like image 795
Flowerfairy Avatar asked Dec 08 '12 23:12

Flowerfairy


1 Answers

If you prefer the C++ idioms, use std::vector<double> and return that at the end where it will be converted via an implicit wrap() to an R vector. You could also use Armadillo or Eigen vectors via RcppArmadillo and RcppEigen.

Our objects are shallow wrappers around the R object, so push_back on, say, a Rcp::NumericVector always needs a full copy. That is known and documented.

Edit: So for completeness, here is an example using RcppArmadillo:

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

// [[Rcpp::export]]
arma::vec shrink(arma::vec x) {
    arma::vec y = x;
    y.resize( y.size()-2 );
    return y;
}

which we can deploy via

R> Rcpp::sourceCpp('/tmp/vec.cpp')
R> shrink(1:10)
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]    4
[5,]    5
[6,]    6
[7,]    7
[8,]    8
R> 
like image 167
Dirk Eddelbuettel Avatar answered Oct 04 '22 21:10

Dirk Eddelbuettel