[Rcpp-devel] Filling NumericMatrix with NumericVectors with apply by row/column?

Romain Francois romain at r-enthusiasts.com
Tue Sep 21 13:34:27 CEST 2010

Le 21/09/10 13:20, Christian Gunning a écrit :
> On Tue, Sep 21, 2010 at 2:56 AM, Romain Francois
> <romain at r-enthusiasts.com>  wrote:
>>>> Sure. I need to think a little bit more about how to do Rcpp::Array, etc
>>>> ...
>>>> because an Array could have an arbitrary number of dimensions.
>>>> Perhaps embedding information into the class would work.
>>>> // make an array of 3 dimensions, etc ...
>>>> Rcpp::Array<3>    ret( y ) ;
> Maybe solving the just the 3D case instead of n-D solve the majority
> of use cases?
>>> Yes, I've been thinking similarly about an Indexer class.  Accounting
>>> for a variable number of dimensions looks unpleasantly messy.
>> Yes. Feel free to share thoughts on that.
> Since an R-style mat(2,) is illegal, perhaps a simple solution is
> using booleans in the index position to indicate "all",   This solves
> a decent range of use cases, and should be accessible to the "native
> R" crowd. Here's a simple one:
> NumericMatrix ret(inmat);
> double lambda = as<double>(inlambda);
> int nr = ret.nrows();
> int nc = ret.ncols();
> int i;
> for (i=0; i<nr; i++) {
>    ret(i,true) = rpois(nc, lambda);
> };

I don't like that. I'd rather go with a dummy class.

class Empty{} ;

and have something like this:

ret( i, Empty() ) = ...

Or perhaps use the "_" thing :

ret( i, _ ) = ...

Or perhaps have this syntax :

ret.row(i) = ...

We aleardy have row member function that returns a Row object, but it 
currently does not have a operator=, that could be taken care of.

> The next logical extension of matrix/array indexing beyond boolean
> would be to allow NumericVectors in each of the index positions.  At
> this point, though, there's an explosion of over-loaded functions - a
> 3D Num myArray(x, y, z) gives 27 separate functions for x,y,z chosen
> from {bool, int, NumericVector}, plus NumericMatrix and NumericVector.
>   Here's where an indexer class starts to make sense - unified
> constructors, along with clear dimensionality of the indexer and
> simple checks of dimensional conformance between indexer and indexed.


> As a side-note, I just spent some time with arma, and was sad to find
> that arma_mat.insert_rows(atrow, rowvec) extends arma_mat, with no
> apparent way to do row/col-level in-place replacement. So, at least
> we're not whipping a dead horse.
> Can you point me to the relevant NumericMatrix(i,j) indexer code?

Look for the "offset" member functions in

This is what is used by operator()(int,int) in Matrix.h:

> thanks much,
> Christian

Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
|- http://bit.ly/cCmbgg : Rcpp 0.8.6
|- http://bit.ly/bzoWrs : Rcpp svn revision 2000
`- http://bit.ly/b8VNE2 : Rcpp at LondonR, oct 5th

More information about the Rcpp-devel mailing list