gpt4 book ai didi

r - 具有未知变量集的 expand.grid

转载 作者:行者123 更新时间:2023-12-04 02:10:23 24 4
gpt4 key购买 nike

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

df <- expand.grid(1:3, 1:3)
df <- expand.grid(1:3, 1:3, 1:3)

我想要的是一个通用函数,它接受 1 个参数(向量数)并返回适当的数据框。

combinations <- function(n) {
return(expand.grid(0, 1, ... n))
}

这样

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

等等

最佳答案

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

关于r - 具有未知变量集的 expand.grid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com