[Rcpp-devel] Dealing with 2-dimensional vectors

Romain Francois romain at r-enthusiasts.com
Mon Feb 15 09:15:18 CET 2010


On 02/15/2010 06:42 AM, Leo Alekseyev wrote:
> Hi all,
>
> I got a chance to play with Rcpp some more this weekend.  I like it!

Cool

> The one thing that I found a little awkward, however, is dealing with
> matrices -- while the new API's SimpleVector indexes them just fine, I
> wish it had provided accessors similar to the old API's
> RcppMatrix<T>.rows()/cols().

That's a good idea. I'll probably make them lhs usable, so that one can do

x.cols() = 5 ;

And I think I prefer ncols and nrows (with the initial n), as this is 
closest to R functions ncols and nrows.

I've put it up as a feature request on r-forge:
https://r-forge.r-project.org/tracker/index.php?func=detail&aid=822&group_id=155&atid=640

> I can get the dimensions attribute via Rcpp::RObject's attr() method,
> but that took some digging to figure out -- mostly because I can't
> seem to get the cast operator to work properly.  Here is how I get the
> dimensions currently:
>
> Rcpp::RObject::AttributeProxy sa_dims_ap(sig_actions.attr("dim"));
> vector<int>  sa_dims2(Rcpp::as<  vector<int>  >(sa_dims_ap));
> Rprintf("sig_actions has dims %d,%d\n",sa_dims2[0],sa_dims2[1]);

This needs better documentation, but what you can do is :

vector<int> dims = sig_actions.attr("dim") ;

This works for me ;

require( inline )
require( Rcpp )

funx <- cfunction(signature(x="matrix"), '
         IntegerVector mat(x);
         std::vector<int> dims = mat.attr("dim") ;
         std::cout << "nrows = " << dims[0] << " , ncols = " << dims[1] 
<< std::endl ;
         return R_NilValue ;
', Rcpp = TRUE, includes = "using namespace Rcpp;" )

 > funx( diag(4) )
nrows = 4 , ncols = 4
NULL


> This seems to involve a cast to SEXP via AttributeProxy's operator
> SEXP().  The following, however, doesn't compile:
> vector<int>  sa_dims3((vector<int>)sa_dims_ap);
> Rprintf("sig_actions has dims %d,%d\n",sa_dims3[0],sa_dims3[1]);
>
> TradingLoopPCA.cpp:257: error: call of overloaded
> ‘vector(Rcpp::RObject::AttributeProxy&)’ is ambiguous

The proxy classes are designed to be invisible, you should not really 
access them directly.

> Any pointers on what I'm doing wrong here?
>
> Thanks,
> --Leo



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



More information about the Rcpp-devel mailing list