[R] yet another vectorization question
adi at roda.ro
Tue Jan 31 17:35:08 CET 2006
On Tuesday 31 January 2006 06:55, Gabor Grothendieck wrote:
> On 1/30/06, Patricia J. Hawkins <phawkins at connact.com> wrote:
> > [...snip...]
> > #which generalizes to:
> > bb <- matrix(1:50, ncol=10, nrow=5, byrow=TRUE)
> > bv <- as.vector(bb)
> > ai <- as.vector(aa) + rep((1:nrow(aa)-1)*10, each=3)
> > bv[ai] <- c(0,1,0)
> > bb <- matrix(bv, ncol=10, nrow=5, byrow=TRUE)
> > bb
> Try this:
> bb <- matrix(NA, ncol=10, nrow=5)
> bb[cbind(c(col(aa)), c(aa))] <- c(0,1,0)
Thank you very much both, I had a very good time exercising your solutions.
The "col" fuction especially is useful (and insightful).
I wrote a working solution based on this type of matrix indexing, which is...
unfortunately... _slower_ than the "for" loop, especially in large loops.
It seems that creating the necessary row and column indexes to cbind is much
slower than copying chunks of data at certain columns:
> library(combinat) # for the combn function
 6.12 0.39 6.54 0.00 0.00
 8.62 0.27 8.91 0.00 0.00
If anyone interested, I uploaded both functions here:
Arhiva Romana de Date Sociale
Bd. Schitu Magureanu nr.1
050025 Bucuresti sectorul 5
Tel./Fax: +40 21 3126618 \
+40 21 3120210 / int.101
More information about the R-help