Hello Søren,
This is easy templating:
template <int RTYPE>
Matrix<RTYPE> vec2matrix(Vector<RTYPE> x, int nrow, int ncol) {
return Matrix<RTYPE>(nrow, ncol, x.begin());
}
will work for NumericVector, IntegerVector, CharacterVector, ...
Romain
Le 31/05/13 11:08, Søren Højsgaard a écrit :
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:[email protected]]
Sent: 31. maj 2013 03:01
To: Søren Højsgaard
Cc: [email protected]
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()); }
--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
R Graph Gallery: http://gallery.r-enthusiasts.com
blog: http://blog.r-enthusiasts.com
|- http://bit.ly/Zs97qg : highlight 0.4.1
`- http://bit.ly/10X94UM : Mobile version of the graph gallery
_______________________________________________
Rcpp-devel mailing list
[email protected]
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel