How to compute the grand sum of a matrix?

时间:2015-05-24 21:25:43

标签: r pseudocode

I have a matrix of size 4 x 10. I want to compute the sum all possible entries of the sum. In other words, if you have a 2 x 2 matrix

2 3
4 1

then there are 2^2 sums (2 + 3, 2 + 1) and (4 + 3, and 4 + 1). Similarly, if you have a 2 x 3 matrix, there would be 2^3 = 8 total sums. Duplicates are allowed. Since my matrix is a 4 x 10, this has 1,048,576 total sums.

How exactly do I compute this in R? Pseudocode is also fine since I am fairly sure I can translate into R. But specialized R packages/functions would be better.

2 个答案:

答案 0 :(得分:7)

A terse way to achieve this for a matrix with any number of columns would be with:

rowSums(expand.grid(as.data.frame(m)))

as.data.frame(m) converts your matrix to a data.frame, which means it can be directly passed to the expand.grid function, which will operate on each column. rowSums efficiently computes the row sums of the result, which will result in significant efficiency gains compared to using apply with function sum:

m <- matrix(1:40, nrow=4)
system.time(apply(expand.grid(m[,1],m[,2],m[,3],m[,4],m[,5],m[,6],m[,7],m[,8],m[,9],m[,10]),1,sum))
#    user  system elapsed 
#   4.866   0.108   4.971 
system.time(rowSums(expand.grid(as.data.frame(m))))
#    user  system elapsed 
#   0.141   0.030   0.171

Edit: As suggested by @Roland, this is not particularly memory efficient because it takes the full cross product of the columns before performing any additions. A harder to read but more memory efficient version would be:

Reduce(function(x, y) rowSums(expand.grid(x, y)), as.data.frame(m))

答案 1 :(得分:2)

What about this?

m <- matrix(c(2,3,4,1), ncol = 2, byrow = T)
apply(expand.grid(m[,2],m[,1]),1,sum)
[1] 5 3 7 5