Reputation: 143
I want to create a function which creates all possible permutations of distinct vectors with elements -1,0,1
for different size vectors.
e.g. for vectors of size 2 then i'd have 3^2 vectors
. This is easy to write down as below, but if i want to do it for vectors of size 6, i'd have to write 729.
x1 = c(1,1)
x2= c(1,0)
x3 = c(1,-1)
x4 = c(0,0)
x5 = c(0,1)
x6 = c(0,-1)
x7= c(-1,1)
x8 = c(-1,0)
x9 = c(-1,-1)
For size 3 vectors...
(1,1,1)
(1,1,0)
(1,1,-1)
(1,0,0)..... etc
Any ideas how can I make this more simplified? Thanks.
Upvotes: 1
Views: 50
Reputation: 24838
Here's one approach with expand.grid
.
expand.grid(c(-1:1),c(-1:1),c(-1:1))
Or for arbitrary length vectors.
expand.grid(rep(list(c(-1:1)),4))
Var1 Var2 Var3 Var4
1 -1 -1 -1 -1
2 0 -1 -1 -1
3 1 -1 -1 -1
4 -1 0 -1 -1
5 0 0 -1 -1
6 1 0 -1 -1
7 -1 1 -1 -1
8 0 1 -1 -1
9 1 1 -1 -1
10 -1 -1 0 -1
Upvotes: 3