expand.grid包含未知变量集

rob*_*bie 2 r

因此,expand.grid返回传递的向量的所有组合的df.

df <- expand.grid(1:3, 1:3)
df <- expand.grid(1:3, 1:3, 1:3)
Run Code Online (Sandbox Code Playgroud)

我想要的是一个带有1个参数(向量数)并返回适当数据帧的通用函数.

combinations <- function(n) {
    return(expand.grid(0, 1, ... n))
}
Run Code Online (Sandbox Code Playgroud)

这样

combinations(2) returns(expand.grid(1:3, 1:3))
combinations(3) returns(expand.grid(1:3, 1:3, 1:3))
combinations(4) returns(expand.grid(1:3, 1:3, 1:3, 1:3))
Run Code Online (Sandbox Code Playgroud)

等等

Tho*_*mas 6

combinations <- function(n)
    expand.grid(rep(list(1:3),n))

> combinations(2)
  Var1 Var2
1    1    1
2    2    1
3    3    1
4    1    2
5    2    2
6    3    2
7    1    3
8    2    3
9    3    3
> combinations(3)
   Var1 Var2 Var3
1     1    1    1
2     2    1    1
3     3    1    1
4     1    2    1
5     2    2    1
6     3    2    1
7     1    3    1
8     2    3    1
9     3    3    1
10    1    1    2
11    2    1    2
12    3    1    2
13    1    2    2
14    2    2    2
15    3    2    2
16    1    3    2
17    2    3    2
18    3    3    2
19    1    1    3
20    2    1    3
21    3    1    3
22    1    2    3
23    2    2    3
24    3    2    3
25    1    3    3
26    2    3    3
27    3    3    3
Run Code Online (Sandbox Code Playgroud)