本文介绍了动态参数expand.grid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 expand.grid 生成矢量的所有元素对,例如:

I am using expand.grid to generate all of the pairs of the elements of a vector, such as:

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

其中给出:

  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

现在,说我想要相同的东西,但我使用三胞胎

Now, say I want the same thing but with triplets I use

expand.grid(v,v,v)

如何将其推广为n个元组,以便可以使用 new.expand.grid(v,5)并得到结果的 expand.grid(v,v,v,v,v)吗?

How would I go about generalizing this to n-tuples so that I can use new.expand.grid(v,5) and have the result of expand.grid(v,v,v,v,v)?

推荐答案

expand.grid 可以将列表作为其输入,所以复制

expand.grid can take a list as its input, so what about replicate?

expand.grid(replicate(3, v, simplify=FALSE))






作为功能,很有趣(尽管我知道您会知道如何做到):


For fun, as a function (though I know you would know how to do this):

new.expand.grid <- function(input, reps) {
  expand.grid(replicate(reps, input, simplify = FALSE))
}

new.expand.grid(c(1, 2), 4)
#    Var1 Var2 Var3 Var4
# 1     1    1    1    1
# 2     2    1    1    1
# 3     1    2    1    1
# 4     2    2    1    1
# 5     1    1    2    1
# 6     2    1    2    1
# 7     1    2    2    1
# 8     2    2    2    1
# 9     1    1    1    2
# 10    2    1    1    2
# 11    1    2    1    2
# 12    2    2    1    2
# 13    1    1    2    2
# 14    2    1    2    2
# 15    1    2    2    2
# 16    2    2    2    2

这篇关于动态参数expand.grid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 18:16