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


assume have 3 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 find possible combinations of column 1 (characters or names) while summing columns 2 , 3. result single matrix length equal total number of possible combinations, in case 6. result 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 not know how add table in question, otherwise show more descriptively. thank in advance.

you mixing character , numeric values in matrix , coerce elements character. better define matrix numeric , keep character values 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 matrices in list mlist<-list(a,b,c) 

then use map, reduce , lapply magic:

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

finally, build 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 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -