Search code examples
rmatrixvectorstatisticsscientific-computing

Manipulating entries of matrices in R


I have a matrix, say 10x10, and I want to make each row entry to be the sum of all entries in that particular row, e.g. all entries in row1 takes the value of the sum of row1, all entries in row2 takes the value of the sum of row two and so on.


Solution

  • Take a 3x3 matrix for example:

    x <- matrix(1:9, 3, 3, T)
    x
    
    #      [,1] [,2] [,3]
    # [1,]    1    2    3
    # [2,]    4    5    6
    # [3,]    7    8    9
    
    x[] <- rowSums(x)
    x
    
    #      [,1] [,2] [,3]
    # [1,]    6    6    6
    # [2,]   15   15   15
    # [3,]   24   24   24