Reputation: 77
I have a list of matrix, e.g. list(M1,M2,M3,M4)
I would like to get a matrix that add all the matrix M1+M2+M3+M4
and divide each row by rowSums(M1)+rowSums(M2)+rowSums(M3)+rowSums(M4)
.
Here an example list,
lst <- list(M1 = matrix(c(1,4,2,5), 2, 2), M2 = matrix(c(2,6,3,7), 2, 2))
lst
#> $M1
#> [,1] [,2]
#> [1,] 1 2
#> [2,] 4 5
#>
#> $M2
#> [,1] [,2]
#> [1,] 2 3
#> [2,] 6 7
where my desired outcome would be,
(1+2)/((2+1)+(2+3)) = 0.375 (2+3)/((2+1)+(2+3)) = 0.625
(4+6)/((6+7)+(4+5)) = 0.4545455 (5+7)/((6+7)+(4+5)) = 0.5454545
Upvotes: 1
Views: 68
Reputation: 12559
You can use a 3-dimensional array and apply()
M1 <- matrix(c(1,4,2,5), 2)
M2 <- matrix(c(2,6,3,7), 2)
L <- list(M1, M2)
M <- array(unlist(L), dim=c(2,2,2)) # or: M <- array(c(M1, M2), dim=c(2,2,2))
apply(M, 1:2, sum) / apply(M, 1, sum)
# > apply(M, 1:2, sum) / apply(M, 1, sum)
# [,1] [,2]
# [1,] 0.3750000 0.6250000
# [2,] 0.4545455 0.5454545
and in rowSums notation (thx to user20650):
rowSums(M, dims=2) / rowSums(M)
Upvotes: 3
Reputation: 887048
We can try
Reduce(`+`, lst)/ sum(sapply(lst, rowSums))
Or
Reduce(`+`, lst)/ sum(unlist(lst))
Based on the update by the OP (using the OP's dataset)
Reduce(`+`, lst)/rowSums(sapply(lst, rowSums))
# [,1] [,2]
#[1,] 0.3750000 0.6250000
#[2,] 0.4545455 0.5454545
lst <- list(matrix(1:16, 4, 4), matrix(1:16, 4, 4))
Upvotes: 5