JmO
JmO

Reputation: 572

get colsum of every possible row combination

Hello I have a problem of how to sum up every possible combination of rows.

Consider I have the matrix:

M<-replicate(5, rnorm(10))

now I want a universal solution to get colSums vectors saved in a list or data frame of all possible row combination: eg some examples :

colsum of row 1 + row 2

colsum of row 1 + row 3 ..

row 2 + row 3

row 2 + row 4 ..

row 1 + row 2 + row 3 ..

row 4 + row 7 + row 10 ...

row 1 + row 2 + row 3 + row 4 + row 5 + row6 + row 7 + row 8 +row 9 + row 10

does anyone know a solution for that? Many thanks

Upvotes: 0

Views: 141

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226192

set.seed(101)
M <- replicate(5, rnorm(10))

A function to get the vector of column sums of a specified set of rows (and label which rows are summed)

cs <- function(cc) colSums(M[cc,])

Test it out with rows 1 and 2:

cs(c(1,2))
##         1         2 
##  2.450401 -4.396749 

This will get all N-way combinations:

csN <- function(N) {
     cc <- combn(1:nrow(M),N,FUN=cs,simplify=FALSE)
     names(cc) <- combn(1:nrow(M),N,FUN=paste,collapse=",")
     return(cc)
}

This makes a list of all of the combinations and sticks them together ...

do.call("c",lapply(2:nrow(M),csN))
## quote function name for safety (fails if a vble called c exists)

## $`1,2`
## [1]  0.2264254 -0.2683963  0.5447664  1.1740892  1.2406726
## 
## $`1,3`
## [1] -1.0009803  1.9542036 -0.4317362  1.9028030 -1.8368686
## 
## ...
##
## $`2,3,4,5,6,7,8,9,10`
## [1]  2.7764374 -4.9231973 -0.3762125 -0.4554264 -4.6341908
## 
## $`1,2,3,4,5,6,7,8,9,10`
## [1]  2.4504010 -4.3967492 -0.5399682  0.4395108 -4.1517320

Upvotes: 5

Related Questions