I have two vectors and I am trying to find all unique combinations of 3 elements from vector1 and 2 elements from vector2. I have tried the following code.
V1 = combn(1:5, 3) # 10 combinations in total
V2 = combn(6:11, 2) # 15 combinations in total
How to combine V1 and V2 so that there are 10 * 15 = 150 combinations in total? Thanks.
You can use expand.grid()
:
g <- expand.grid(seq_len(ncol(V1)), seq_len(ncol(V2)))
V3 <- rbind(V1[, g[, 1]], V2[, g[, 2]])
The result is in a similar format as V1
and V2
, i.e. a 5 × 150 matrix (here printed transposed):
head(t(V3))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 3 6 7
# [2,] 1 2 4 6 7
# [3,] 1 2 5 6 7
# [4,] 1 3 4 6 7
# [5,] 1 3 5 6 7
# [6,] 1 4 5 6 7
dim(unique(t(V3)))
# [1] 150 5
And a generalized approach that can handle more than two initial matrices of combinations, stored in a list V
:
V <- list(V1, V2)
g <- do.call(expand.grid, lapply(V, \(x) seq_len(ncol(x))))
V.comb <- do.call(rbind, mapply('[', V, T, g))
identical(V.comb, V3)
[1] TRUE