Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

r - Dynamic arguments to 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)

Which gives:

  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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...