Dear list,<br><br>I'm amazed at the ability to use the apply family in Rcpp. Yet I'm still<br>unsure of the best way to assign NumericVector objects into<br>NumericMatrix objects. Must this be done element-by-element, or is<br>
there something equivalent to R's MyMatrix[,1] = MyColVector? <br>(As an aside, are both mymatrix[i,j] and mymatrix(i,j) equivalent? It<br>seems that I've seen them used interchangably on the list.)<br><br>A simple example of what I'm aiming for:<br>
Make an n*n matrix, and use sapply to perform a vector operation by<br>row, here constructing a vector of length n full of zeros.<br><br>// a simple vector-returning function<br>NumericVector zeros( int n){<br> NumericVector ret(n);<br>
ret = 0;<br> return ret;<br>}<br><br>// sapply version, doesn't work but is easy to read<br>SEXP foo( int n ){<br> NumericVector x(n);<br> x = n;<br> NumericMatrix xx(n,n) ;<br> // possible to assign by row or column?<br>
xx = sapply( x, zeros ) ;<br> return(xx);<br>}<br><br>// the looped version, where xx[,i] is not syntactically valid<br>SEXP foo1( int n ){<br> NumericVector x(n);<br> int i;<br> NumericMatrix xx(n,n) ;<br> // possible to assign by row or column?<br>
for (i =0; i<n; i++) {<br> xx[,i] = zeros(n) ;<br> }<br> return(xx)<br>}<br><br><br>// syntactically valid, element-wise assignment<br>SEXP foo2( int n ){<br> NumericVector x(n);<br> int i, j;<br> NumericMatrix xx(n,n) ;<br>
// possible to assign by row or column?<br> for (i=0; i<n; i++) {<br> x = zeros(n) ;<br> for (j=0; j<n; j++) {<br> xx(i,j) = x[j]<br> }<br> }<br> return(xx)<br>}<br><br>thanks so much,<br>Christian Gunning<br>
-- <br>A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!<br><br>