[R] incrementing matrix elements more efficiently
david h shanabrook
dhshanab at acad.umass.edu
Sun Aug 15 02:43:14 CEST 2010
I need to increment cells of a matrix (collusionM). The indexes to increment are in an index (matchIndex). This is sample code
library(seqinr)
library(Matrix)
x <- "abcabcabc"
mx <- s2c(x)
collisionM <- Matrix(0,nrow=10, ncol=10, sparse=TRUE)
matchIndex <- list()
rows <- length(mx)
for (j in 1:(rows)) matchIndex[[j]] <- which(mx[j]==mx)
for (j in 1:(rows)) collisionM[j,matchIndex[[j]]] <- collisionM[j,matchIndex[[j]]] + 1
Works fine, except with my data (rows=32000) it is too slow. The problem is the second for loop, where it increments the index of the sparse matrix; this needs to be rewritten so it is more efficient. Any ideas?
More information about the R-help
mailing list