[Rcpp-devel] Turning a vector into a matrix

Søren Højsgaard sorenh at math.aau.dk
Fri May 31 02:23:12 CEST 2013


Dear all 

Apologies for a trivial question. I want to turn the vector

vec <- 1:4

into a matrix
1 3
2 3

I do:
src1 <-'
NumericVector vec(vec_);	
NumericMatrix mat( as<int>(nrow_), as<int>(ncol_) );
for(int ii=0; ii<mat.rows()*mat.cols(); ii++){
  mat[ii] = vec[ii];
}
return(wrap(mat));
'

vec2matrix <- cxxfunction(signature(vec_="",nrow_="", ncol_=""), 
	plugin="Rcpp", body=src1, verbose=T)

vec <- 1:4 
(ans<-vec2matrix(vec,2,2))

     [,1] [,2]
[1,]    1    3
[2,]    2    4

But - isn't there a much simpler way of doing so? I've looked at RcppArmadillo, but have been unable to find an elegant way.

Best regards
Søren




More information about the Rcpp-devel mailing list