Reputation: 969
I'd like to know if there's any way to use the expand.grid() function (or any other one) to generate all the possible combinations for a specified number of sequences. The latter is given by the user.
Desired result. For example,
expand.grid(0:1, 0:1)
Var1 Var2
1 0 0
2 1 0
3 0 1
4 1 1
expand.grid(0:1, 0:1, 0:1)
Var1 Var2 Var3
1 0 0 0
2 1 0 0
3 0 1 0
4 1 1 0
5 0 0 1
6 1 0 1
7 0 1 1
8 1 1 1
expand.grid(0:1, 0:1, 0:1, ...)
Var1 Var2 Var3 ...
1 0 0 0 ...
2 1 0 0 ...
3 0 1 0 ...
4 1 1 0 ...
5 0 0 1 ...
6 1 0 1 ...
7 0 1 1 ...
8 1 1 1 ...
. . . .
. . . .
. . . .
NOTE: the implementation is not limited to 0-1 sequences, so it should also work for something like expand.grid(0:1, 0:5, 2:4, 3:5)
My implementation. I was trying something like this:
expand.grid(rep(0:1, 3))
But R interprets this as a single sequence:
Var1
1 0
2 1
3 0
4 1
5 0
Any help would be really appreciated!
Upvotes: 1
Views: 638
Reputation: 887118
We can rep
the list
and then do expand.grid
expand.grid(rep(list(0:1),3))
# Var1 Var2 Var3
#1 0 0 0
#2 1 0 0
#3 0 1 0
#4 1 1 0
#5 0 0 1
#6 1 0 1
#7 0 1 1
#8 1 1 1
Or another option would be using replicate
with simplify=FALSE
to return a list
output and then use expand.grid
expand.grid(replicate(3, 0:1, simplify=FALSE))
Upvotes: 5