在R中迭代使用expand.grid

jro*_*las 1 iteration combinations r

我想知道是否有任何方法可以使用expand.grid()函数(或任何其他函数)为指定数量的序列生成所有可能的组合.后者由用户给出.

期望的结果.例如,

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 ...
.    .    .    .
.    .    .    .
.    .    .    .
Run Code Online (Sandbox Code Playgroud)

注意:实现不限于0-1序列,因此它也适用于类似的东西expand.grid(0:1, 0:5, 2:4, 3:5)

我的实施.我正在尝试这样的事情:

expand.grid(rep(0:1, 3))
Run Code Online (Sandbox Code Playgroud)

但是R将此解释为单个序列:

  Var1
1    0
2    1
3    0
4    1
5    0
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激!

akr*_*run 5

我们可以replist,然后做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
Run Code Online (Sandbox Code Playgroud)

或者另一个选项是使用replicatewith simplify=FALSE来返回list输出然后使用expand.grid

expand.grid(replicate(3, 0:1, simplify=FALSE))
Run Code Online (Sandbox Code Playgroud)