Will T-E
Will T-E

Reputation: 637

How to sum all combinations of rows in Matrix?

I'm looking to sum all possible combinations of rows in a matrix. A function similar to rowSums() function but instead of producing nrow()sums, it would produce nrow() ^ nrow() sums.

For example:

set.seed(10)
dummymat <-  matrix(floor(runif(9, 0, 2)), nrow = 3, ncol = 3)

produces the matrix:

     [,1] [,2] [,3]
[1,]    1    1    0
[2,]    0    0    0
[3,]    0    0    1

To find every possible row-sum of the matrix, the following very inefficient code could be written:

allrowsums <- c()

for(i in 1:nrow(dummymat)) {
  firstcolval <- dummymat[i,1]
  for(j in 1:nrow(dummymat)) {
    secondcolval <- dummymat[j,2]
    for(k in 1:nrow(dummymat)) {
      thirdcolval <- dummymat[k,3]
      rowsum <- firstcolval + secondcolval + thirdcolval
      allrowsums <- append(allrowsums,rowsum)
  }
 }
}

Which gives the following output:

[1] 2 2 3 1 1 2 1 1 2 1 1 2 0 0 1 0 0 1 1 1 2 0 0 1 0 0 1

What more-succinct code could I write for much larger matrices?

Upvotes: 3

Views: 1868

Answers (1)

Djork
Djork

Reputation: 3369

You can use expand.grid to create a data frame of all combinations of column-wise elements.

dummymat_expand <- expand.grid(x=dummymat[,1], y=dummymat[,2], z=dummymat[,3])

From here, you can just call rowSums to get all possible sum combinations.

rowSums(dummymat_expand)

Edited to answer question. To apply code to matrices with variable column length, note that expand.grid can take vectors, factors or a list as inputs. You can therefore create a list of column elements to feed to expand.grid

# create a list of column elements
dummymat_column_list <- lapply(1:ncol(dummymat), function(x) dummymat[, x])
expand.grid(dummymat_column_list)

Upvotes: 5

Related Questions