-2

I have two matrices of arbitrary sizes, e.g. matrix 1 (n * m) and matrix 2 (k * l). Is there a (convenient) way in R to cbind them row-by-row, to form a (n * k) * (m + l) matrix where each row of matrix 1 has a chance to be cbinded to each row of matrix 2? It is a complete row-by-row combination so the order does not matter.

For example, is there a function f such that: please click to view

Thanks!

De Novo
  • 7,120
  • 1
  • 23
  • 39
Ken Chen
  • 7
  • 3

3 Answers3

1

In the future, please include example data that is copy/pasteable, not just a picture.

m1 = matrix(1:6, ncol = 2)
m2 = matrix(7:12, ncol = 3)

combos = expand.grid(1:nrow(m1), 1:nrow(m2))
cbind(m1[combos$Var1, ], m2[combos$Var2, ])
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    4    7    9   11
# [2,]    2    5    7    9   11
# [3,]    3    6    7    9   11
# [4,]    1    4    8   10   12
# [5,]    2    5    8   10   12
# [6,]    3    6    8   10   12
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

There might be a better solution, but this works for smaller size problems:

A <- matrix(c(1,2,3,2,3,4), nrow = 3)
B <- matrix(c(5,6,6,7,7,8), nrow = 2)

temp <- lapply(1:nrow(A), function(x){
  C = apply(B, 1, function(y){
    c(A[x,],y)
  })
  return(t(C))
})

output <- do.call(rbind, temp)
0
cbind(A[rep(1:(x<-nrow(A)),each=y<-nrow(B)),],B[rep(1:y,x),])
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    5    6    7
[2,]    1    2    6    7    8
[3,]    2    3    5    6    7
[4,]    2    3    6    7    8
[5,]    3    4    5    6    7
[6,]    3    4    6    7    8

Break down:

  x=nrow(A)
  y=nrow(B)
  cbind(A[rep(1:x,each=y),],B[rep(1:y,x),])
Onyambu
  • 67,392
  • 3
  • 24
  • 53