Pat
Pat

Reputation: 3

How to compute all possible combinations of multiple vectors/matrices of different sizes and sum up columns simultaneously?

Assume I have three matrices...

A=matrix(c("a",1,2),nrow=1,ncol=3)
B=matrix(c("b","c",3,4,5,6),nrow=2,ncol=3)
C=matrix(c("d","e","f",7,8,9,10,11,12),nrow=3,ncol=3)

I want to find all possible combinations of column 1 (characters or names) while summing up columns 2 and 3. The result would be a single matrix with length equal to the total number of possible combinations, in this case 6. The result would look like the following matrix...

Result <- matrix(c("abd","abe","abf","acd","ace","acf",11,12,13,12,13,14,17,18,19,18,19,20),nrow=6,ncol=3)

I do not know how to add a table in to this question, otherwise I would show it more descriptively. Thank you in advance.

Upvotes: 0

Views: 1246

Answers (1)

nicola
nicola

Reputation: 24490

You are mixing character and numeric values in a matrix and this will coerce all elements to character. Much better to define your matrix as numeric and keep the character values as the row names:

A <- matrix(c(1,2),nrow=1,dimnames=list("a",NULL))
B <- matrix(c(3,4,5,6),nrow=2,dimnames=list(c("b","c"),NULL))
C <- matrix(c(7,8,9,10,11,12),nrow=3,dimnames=list(c("d","e","f"),NULL))
#put all the matrices in a list
mlist<-list(A,B,C)

Then we use some Map, Reduce and lapply magic:

res <-  Reduce("+",Map(function(x,y) y[x,],
               expand.grid(lapply(mlist,function(x) seq_len(nrow(x)))),
               mlist))

Finally, we build the rownames

rownames(res)<-do.call(paste0,expand.grid(lapply(mlist,rownames)))
#    [,1] [,2]
#abd   11   17
#acd   12   18
#abe   12   18
#ace   13   19
#abf   13   19
#acf   14   20

Upvotes: 2

Related Questions