[Rcpp-devel] Turning a vector into a matrix
Søren Højsgaard
sorenh at math.aau.dk
Fri May 31 11:08:45 CEST 2013
Dear all,
Dirk: Thanks for the reply :).
I shall dare to ask a "bonus question": I've played around with templating so that I get the right output type. I know (thanks to an earlier reply by Romain) how to do so using SEXP's but if I am constructing a utility function to be used on c++ objects, I can't that to work. What I am after should mimic the following such that the output type is determined by the input type:
NumericMatrix vec2matrix(NumericVector x, int nrow, int ncol) {
return NumericMatrix(nrow, ncol, x.begin());
}
IntegerMatrix vec2matrix(IntegerVector x, int nrow, int ncol) {
return IntegerMatrix(nrow, ncol, x.begin());
}
Any help would be more than welcome.
Best regards
Søren
-----Original Message-----
From: Dirk Eddelbuettel [mailto:edd at debian.org]
Sent: 31. maj 2013 03:01
To: Søren Højsgaard
Cc: rcpp-devel at r-forge.wu-wien.ac.at
Subject: Re: [Rcpp-devel] Turning a vector into a matrix
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