# Re: [R] yet another vectorization question

From: Patricia J. Hawkins <phawkins_at_connact.com>
Date: Tue 31 Jan 2006 - 14:37:41 EST

```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

______________________________________________
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 15:08:54 2006

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