[R] yet another vectorization question

Patricia J. Hawkins phawkins at connact.com
Tue Jan 31 04:37:41 CET 2006


>>>>> "AD" == Adrian Dusa <adi at 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



-- 
Patricia J. Hawkins
Hawkins Internet Applications
www.hawkinsia.com




More information about the R-help mailing list