Re: [R] yet another vectorization question

From: Adrian DUSA <adi_at_roda.ro>
Date: Wed 01 Feb 2006 - 03:35:08 EST

On Tuesday 31 January 2006 06:55, Gabor Grothendieck wrote:
> On 1/30/06, Patricia J. Hawkins <phawkins@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
> system.time(all.expr(LETTERS[1:12]))
[1] 6.12 0.39 6.54 0.00 0.00
> system.time(all.expr2(LETTERS[1:12]))
[1] 8.62 0.27 8.91 0.00 0.00

If anyone interested, I uploaded both functions here: http://www.roda.ro/all.expr.R

Thank you,
Adrian

-- 
Adrian DUSA
Arhiva Romana de Date Sociale
Bd. Schitu Magureanu nr.1
050025 Bucuresti sectorul 5
Romania
Tel./Fax: +40 21 3126618 \
          +40 21 3120210 / int.101

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Wed Feb 01 03:43:47 2006

This archive was generated by hypermail 2.1.8 : Wed 01 Feb 2006 - 08:27:40 EST