Vectorize matrix operation in R
        Posted  
        
            by 
                Fernando
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Fernando
        
        
        
        Published on 2012-07-09T01:37:33Z
        Indexed on 
            2012/07/09
            3:16 UTC
        
        
        Read the original article
        Hit count: 253
        
I have a R x C matrix filled to the k-th row and empty below this row. What i need to do is to fill the remaining rows. In order to do this, i have a function that takes 2 entire rows as arguments, do some calculations and output 2 fresh rows (these outputs will fill the matrix). I have a list of all 'pairs' of rows to be processed, but my for loop is not helping performance:
# M is the matrix
# nrow(M) and k are even, so nLeft is even
M = matrix(1:48, ncol = 3)
# half to fill
k = nrow(M)/2
# simulate empty rows to be filled
M[-(1:k), ] = 0
 cat('before fill')
 print(M)
# number of empty rows to fill
nLeft  = nrow(M) - k
nextRow = k + 1
# list of rows to process (could be any order of non-empty rows)
idxList = matrix(1:k, ncol = 2)
for ( i in 1 : (nLeft / 2))
{
    row1 = M[idxList[i, 1],]
    row2 = M[idxList[i, 2],]
    # the two columns in 'results' will become 2 rows in M
    # fake result, return 2*row1 and 3*row2
    results = matrix(c(2*row1, 3*row2), ncol = 2)
    # fill the matrix
    M[nextRow, ] = results[, 1]
    nextRow = nextRow + 1
    M[nextRow, ] = results[, 2]
    nextRow = nextRow + 1
}
 cat('after fill')
 print(M)
I tried to vectorize this, but failed... appreciate any help on improving this code, thanks!
© Stack Overflow or respective owner