Skip to content
Prev 206142 / 398503 Next

Making routine faster by using apply instead of for-loop

Your code is doing too many needless things.
The following takes about one second on my slow Vista laptop.

n <- 500
mat <- matrix(1:(n*n), n)
v <- n:1
z <- 2*1:(n/2)
w <- c(z, rev(z))
for(i in seq_len(n)){
   for(j in seq_len(n)){
     if(v[j] + w[i] <= n)(mat[i,j] <- NA)
   }
}
rownames(mat) <- v
colnames(mat) <- w

str(mat)

You end up with matrix, but if you really want a data.frame
with duplicate names, that's easy to get. Do you actually
want those row/col names or are they just used to identify
the cells that get NA?

Depending on what you really need, the following may be
good enough; takes about 0.1 seconds.

n <- 500
mat <- matrix(1:(n*n), n)
for(i in 1:(n/2)){mat[i, -(1:(2*i))] <- mat[n+1-i, -(1:(2*i))] <- NA}

  -Peter Ehlers
Etienne Stockhausen wrote: