[Rcpp-devel] Translating between Rcpp Vectors and Matrices?

Kevin Ushey kevinushey at gmail.com
Fri Feb 1 05:15:15 CET 2013


This works great Dirk. Thanks!

-Kevin

On Thu, Jan 31, 2013 at 6:19 PM, Dirk Eddelbuettel <edd at debian.org> wrote:

>
> On 31 January 2013 at 17:41, Kevin Ushey wrote:
> | I was wondering - is there a way to translate between Vectors and
> Matrices? Eg,
> | reinterpreting a 100 length NumericVector as a 10x10 NumericMatrix by
> setting
> | the dimensions explicitly, or something of that form; preferably with a
> minimal
> | amount of copying.
>
> I fear that just setting the dim argument won't be enough as we're strongly
> typed in C++.
>
> | Alternatively, is there a preferred method for constructing a
> NumericMatrix
> | for output from a std::vector?
>
> Yes, there are constructors that that rows, cols and a pointer to the
> contiguous memory.  That is what I would use.  There should be examples
> ploting.  But as a sketch:
>
>    Rcpp::NumericMatrix M(10, 10, X.begin() );
>
> Actually, as it is so cheap to test:
>
>
> -------------------------------------------------------------------------------
> #include <Rcpp.h>
>
> // [[Rcpp::export]]
> Rcpp::NumericMatrix reshapePlusPlus(Rcpp::NumericVector X) {
>   return Rcpp::NumericMatrix(sqrt(X.length()), sqrt(X.length()),
> X.begin());
> }
>
> -------------------------------------------------------------------------------
>
> which pans out:
>
> R> sourceCpp("/tmp/kevin.cpp")
> R>
> R> reshapePlusPlus(1:9)
>      [,1] [,2] [,3]
> [1,]    1    4    7
> [2,]    2    5    8
> [3,]    3    6    9
> R>
>
>
> | The motivation is primarily for reshaping of R objects through Rcpp. I
> wasn't
> | able to find anything specific in the vignettes.
>
> Not sure if this faster than just setting dim in R though....
>
> Dirk
>
> --
> Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130131/acf579fc/attachment.html>


More information about the Rcpp-devel mailing list