Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations of multiple vectors in R

Tags:

r

combinations

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?

like image 720
Michael Avatar asked Nov 12 '11 22:11

Michael


1 Answers

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
like image 161
Gavin Simpson Avatar answered Sep 22 '22 05:09

Gavin Simpson