[Rcpp-devel] Rcpp shortcut for R's as.matrix and as.vector

Romain Francois romain at r-enthusiasts.com
Tue Mar 30 08:44:17 CEST 2010


Le 29/03/10 15:36, Douglas Bates a écrit :
>
> Most Lapack routines for solving linear systems from factorizations
> allow the right hand side to be a matrix, thereby providing for
> solving multiple systems in one  call.  I would like to preserve this
> capability while also allowing for the most common case where the rhs
> is a vector.  Also, I would like to return a vector solution rather
> than a single matrix solution when it is a single column.
>
> I can accomplish these "as.matrix" and "as.vector" translations by
> calling the corresponding R functions.
>
> static Rcpp::Function asMatrix("as.matrix")
> static Rcpp::Function asVector("as.vector")
>
> and using those within Rcpp.  Is there an alternative within Rcpp?

Not really. You can do :

x.attr( "dim" ) = R_NilValue ;

or

x.attr( "dim" ) = IntegerVector::create( 5, 5 ) ;


Here is a sketch for something we might want to add in the Matrix template:

SEXP as_vector(){
	SEXP x = ::Rf_duplicate( m_sexp ) ;
	::Rf_setAttrib( x, ::Rf_install( "dim" ), R_NilValue ) ;
	// perhaps also dimnames
	return x ;
}

or maybe this should return a VECTOR (which is a typedef to the 
appropriate Vector<RTYPE> in Matrix.

I don't really have time to play with this in the coming days, but if 
you try to add the function and some unit tests, I'll take time to 
review them. I could also sketch out Vector::as_matrix but I guess you 
also can.

> I realize that I need to return another object so that it can have a
> different class within C++ but I guess I would like
>
> NumericMatrix mat = Rcpp::as<NumericMatrix>(myNumericVector);

I'm mot sure this will work (actually I'm almost sure this does not, but 
I did not test).

You would essentially be calling the NumericMatrix( SEXP ) constructor 
which would not be happy about the argument not being a matrix.

> or something similar.  It is not a big deal because the calls to the R
> function are not a problem (or I could manipulate the SEXP internally)
> but I'm wondering if I am missing something simple here.


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/OIXN : raster images and RImageJ
|- http://tr.im/OcQe : Rcpp 0.7.7
`- http://tr.im/O1wO : highlight 0.1-5



More information about the Rcpp-devel mailing list