Combinations of multiple vectors in R
12,929
Solution 1
This is a useful case for storing the vectors in a list and using do.call()
to arrange for an appropriate function call for you. expand.grid()
is the standard function you want. But so you don't have to type out or name individual vectors, try:
> l <- list(a = 1:2, b = 3:4, c = 2:3)
> do.call(expand.grid, l)
a b c
1 1 3 2
2 2 3 2
3 1 4 2
4 2 4 2
5 1 3 3
6 2 3 3
7 1 4 3
8 2 4 3
However, for all my cleverness, it turns out that expand.grid()
accepts a list:
> expand.grid(l)
a b c
1 1 3 2
2 2 3 2
3 1 4 2
4 2 4 2
5 1 3 3
6 2 3 3
7 1 4 3
8 2 4 3
Solution 2
This is what expand.grid
does.
Quoting from the help page: Create a data frame from all combinations of the supplied vectors or factors. The result is a data.frame
with a row for each combination.
expand.grid(
c(1, 2),
c(3, 4),
c(2, 3)
)
Var1 Var2 Var3
1 1 3 2
2 2 3 2
3 1 4 2
4 2 4 2
5 1 3 3
6 2 3 3
7 1 4 3
8 2 4 3
Author by
Michael
Updated on July 27, 2022Comments
-
Michael almost 2 years
I'm not sure if permutations is the correct word for this. I want to given a set of n vectors (i.e.
[1,2]
,[3,4]
and[2,3]
) permute them all and get an output of[1,3,2],[1,3,3],[1,4,2],[1,4,3],[2,3,2] etc.
Is there an operation in R that will do this?
-
Gavin Simpson over 12 years@Andrie How embarrassing! Trying to be too clever does have its advantages it would appear. I don't deserve the Accept here though. I shall make amends with some upvotes.
-
user1375871 over 10 yearsHi, I am trying this approach, but am getting the message: "Error in rep.int(rep.int(seq_len(nx), rep.int(rep.fac, nx)), orep) : vector is too large" Are there any alternative ways to do this?
-
sebastian-c over 7 years@user1375871 How large are your vectors?