简体   繁体   中英

Iterative usage of expand.grid in R

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM