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

Christian Gunning xian at unm.edu
Sat Aug 21 23:13:27 CEST 2010


Dear list,

I'm amazed at the ability to use the apply family in Rcpp.  Yet I'm still
unsure of the best way to assign NumericVector objects into
NumericMatrix objects.  Must this be done element-by-element, or is
there something equivalent to R's MyMatrix[,1] = MyColVector?
(As an aside, are both mymatrix[i,j] and mymatrix(i,j) equivalent?  It
seems that I've seen them used interchangably on the list.)

A simple example of what I'm aiming for:
Make an n*n matrix, and use sapply to perform a vector operation by
row, here constructing a vector of length n full of zeros.

// a simple vector-returning function
NumericVector zeros( int n){
 NumericVector ret(n);
 ret = 0;
 return ret;
}

// sapply version, doesn't work but is easy to read
SEXP foo( int n ){
 NumericVector x(n);
 x = n;
 NumericMatrix xx(n,n) ;
 // possible to assign by row or column?
 xx = sapply( x, zeros ) ;
 return(xx);
}

// the looped version, where xx[,i] is not syntactically valid
SEXP foo1( int n ){
 NumericVector x(n);
 int i;
 NumericMatrix xx(n,n) ;
 // possible to assign by row or column?
 for (i =0; i<n; i++) {
   xx[,i] = zeros(n) ;
 }
 return(xx)
}


// syntactically valid, element-wise assignment
SEXP foo2( int n ){
 NumericVector x(n);
 int i, j;
 NumericMatrix xx(n,n) ;
 // possible to assign by row or column?
 for (i=0; i<n; i++) {
   x = zeros(n) ;
   for (j=0;  j<n; j++) {
     xx(i,j) = x[j]
   }
 }
 return(xx)
}

thanks so much,
Christian Gunning
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20100821/33fbcb69/attachment.htm>


More information about the Rcpp-devel mailing list