Is there any function to get the results from multiple rowsum of multiple columns and save it on a new matrix?

Viewed 48

Is there any function to get the results from multiple rows of multiple columns and save it on a new matrix?

Example matrix

 M <- structure(c(1L, 4L, 7L, 2L, 5L, 8L, 3L, 6L, 9L), .Dim = c(3L,3L))
 > M
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

 M_Sum <- empty_matrix
    
 M_Sum = [M[,1]+M[,2] M[,1]+M[,2] M[,2]+M[,3]]

 M_Sum = [3 4 5
          9 10 11
          15 16 17]

the code must be able to do it for n number of columns, the operation performs a combinatorial of size 10C2 the final size of the Sum_Matris must be (10,45)

I have tried

M <- matrix(, nrow = 10, ncol=45)


for(z in 1:45){
  
  for ( i in 1:10){
    k <- i;
    for ( j in k:10){
      
      M[,z] <- R[,i] + R[,j]
      
    }
    
    
  }
  
}
3 Answers

We can use combn with asplit

combn(asplit(M, 2), 2, FUN = function(x) Reduce(`+`, x))
#     [,1] [,2] [,3]
#[1,]    3    4    5
#[2,]    9   10   11
#[3,]   15   16   17

We can create combinations of all the column index in the matrix and add them :

combn(seq(ncol(M)), 2, function(x) M[, x[1]] + M[, x[2]])

#     [,1] [,2] [,3]
#[1,]    3    4    5
#[2,]    9   10   11
#[3,]   15   16   17

We can also use rowSums :

combn(seq(ncol(M)), 2, function(x) rowSums(M[, x]))

data

M <- matrix(1:9, 3, byrow = TRUE)

You can use as.data.frame before using combn, e.g.,

combn(as.data.frame(M),2,rowSums)

which gives

     [,1] [,2] [,3]
[1,]    3    4    5
[2,]    9   10   11
[3,]   15   16   17
Related