Re: [R] yet another vectorization question

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue 31 Jan 2006 - 15:55:02 EST

On 1/30/06, Patricia J. Hawkins <phawkins@connact.com> wrote:
> >>>>> "AD" == Adrian Dusa <adi@roda.ro> writes:
>
> AD> set.seed(5)
> AD> aa <- matrix(sample(10, 15, replace=T), ncol=5)
> AD> bb <- matrix(NA, ncol=10, nrow=5)
> AD> for (i in 1:ncol(aa)) bb[i, aa[, i]] <- c(0, 1, 0)
>
> AD> Is there any possibility to vectorize this "for" loop?
> AD> (sometimes I have hundreds of columns in the "aa" matrix)
>
> Well, coming from ignorance of R, I came up with the below. However,
> it means creating another vector that's the size of aa, so it's not
> clear that it's a win:
>
> #Problem: Indexing bb correctly when vectorized
> #Solution: Add the following matrix to aa:
> # [,1] [,2] [,3] [,4] [,5]
> #[1,] 0 10 20 30 40
> #[2,] 0 10 20 30 40
> #[3,] 0 10 20 30 40
> #
> # or its vector equivalent:
> #
> # rep(0:(ncol(aa)-1)*ncol(bb), each=nrow(aa))
> # > [1] 0 0 0 10 10 10 20 20 20 30 30 30 40 40 40
>
> bb <- matrix(1:50, ncol=10, nrow=5, byrow=TRUE)
> bv <- as.vector(bb)
> ai <- as.vector(aa) + rep(0:4*10, each=3)
> bv[ai] <- c(0,1,0)
> bb <- matrix(bv, ncol=10, nrow=5, byrow=TRUE)
> bb
>
> #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)



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 Tue Jan 31 16:02:18 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:42:15 EST