Jeppe Olsen Jeppe Olsen - 4 days ago 6
R Question

How to sum two matrices by seq_along in r?

I have two matrices that i want to sum

mat1<-matrix(1:4,2,2)
mat2<-matrix(5:8,2,2)
mat1
[,1] [,2]
[1,] 1 3
[2,] 2 4

mat2
[,1] [,2]
[1,] 5 7
[2,] 6 8


what i want is this

mat_sum
[,1] [,2]
[1,] 6 10
[2,] 8 12


I tried

mat_sum <- sapply(seq_along(mat1), function(i)
mat1[[i]]+mat2[[i]])


but then it doesnt return a matrix

[1] 6 8 10 12


How can i get it to return a matrix?

Answer

We can do a regular + which will preserve the matrix format and does the elementwise summation

mat1 + mat2
#     [,1] [,2]
#[1,]    6   10
#[2,]    8   12

If there are many matrices, place it in a list and use Reduce with +

Reduce(`+`, mget(paste0("mat", 1:2)))
Comments