[Rcpp-devel] Turning a vector into a matrix

Dirk Eddelbuettel edd at debian.org
Fri May 31 03:01:11 CEST 2013


Soren,

You missed the most appropriate constructor:  

    template <typename Iterator>
    Matrix( const int& nrows_, const int& ncols, Iterator start ) ;

With that we just do this:

  R> Rcpp::sourceCpp('/tmp/soren.cpp')
  R> soren(1:4,2,2)
       [,1] [,2]
  [1,]    1    3
  [2,]    2    4
  R> 

and the file soren.cpp is below.

Dirk


#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix soren(NumericVector x, int n, int k) {
  return NumericMatrix(n, k, x.begin());
}

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list