Skip to content
Prev 277961 / 398506 Next

place values into a matrix efficiently?

On 20/11/11 16:27, Carl Witthoft wrote:
Yes.  Use ``xymat[m]'' where m is a 2-column matrix of row and column
indices.

E.g.:

xymat <- matrix(0,nrow=10,ncol=10)
x <- 1:10
y <- sample.int(10,10,rep=TRUE)
set.seed(42)
for (j in 1:10) xymat[x[j],y[j]] <- runif(1)

gorp <- matrix(0,nrow=10,ncol=10)
set.seed(42)
gorp[cbind(x,y)] <- runif(10)
all.equal(xymat,gorp) # TRUE!!!

     cheers,

         Rolf Turner