rrbest
rrbest

Reputation: 1789

Merging multiple combination matrices together

I have two matrices built from combinations

mat1 <- combn(10, 2)
mat2 <- combn(20, 3)

mat1 being a 2x45 and mat2 being a 3x1140.

What I want to produce is the possible combinations assuming you take both actions in sequence. So first 10 choose 2, followed immediately by 20 choose 3, what are all the combinations. I would like to produce a matrix which has 5 rows and 51300 columns. The first column values would be (1, 2, 1, 2, 3)

What is the most appropriate way to implement this?

Upvotes: 2

Views: 181

Answers (2)

flodel
flodel

Reputation: 89057

Interesting question. Here is a solution that makes use of a couple Kronecker products:

one1 <- matrix(1, ncol = ncol(mat1))
one2 <- matrix(1, ncol = ncol(mat2))

rbind(mat1 %x% one2, one1 %x% mat2)

or

rbind(one2 %x% mat1, mat2 %x% one1)

depending on which combination matrix you want to recycle first.

Upvotes: 2

Nishanth
Nishanth

Reputation: 7130

Another possible solution using expand.grid:

idx = expand.grid((1:ncol(mat1)),(1:ncol(mat2)))

rbind(mat1[,idx[,1]], mat2[,idx[,2]])

Generalization to any number of matrices:

mat.list <- list(mat1, mat2)
idx <- expand.grid(lapply(lapply(mat.list, ncol), seq_len))
do.call(rbind, mapply(function(x, j)x[, j], mat.list, idx))

Upvotes: 2

Related Questions