Combinations of several vectors in R

I'm not sure if the right words are permutations for this. I want to give a set of n vectors (i.e. [1,2], [3,4]and [2,3]) to rearrange them all and get the output

[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?

+5
source share
2 answers

This is a useful case for storing vectors in a list and use do.call()to organize the corresponding function call for you. expand.grid()is the standard feature you want. But you do not need to enter or specify separate 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, despite all my skills, it turns out that it 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
+9
source

, expand.grid.

: . data.frame .

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
+7

All Articles