Reputation: 3
I need to generate all the combinations of 1:n
repeated n
times. Example with n = 4
:
expand.grid(1:4, 1:4, 1:4, 1:4)
This method, however, will require a lot of typing when n
is a larger number. Is there an efficient way to do this? I Tried paste
and couldn't make it work.
Upvotes: 0
Views: 738
Reputation: 886948
We can rep
licate into a list
and apply the expand.grid
n <- 4
expand.grid(rep(list(seq_len(n)), n))
Or use replicate
expand.grid(replicate(n, seq_len(n), simplify = FALSE))
Upvotes: 4
Reputation: 7597
First off, you are looking for permutations with repetition, not combinations. Secondly, there are several packages for obtaining this efficiently in R
. There is the classical package gtools
and there are the two highly efficient compiled libraries arrangements
and RcppAlgos
(I am the author):
## library(gtools)
gtools::permutations(4, 4, repeats.allowed = TRUE)
## library(arrangements)
arrangements::permutations(4, 4, replace = TRUE)
## library(RcppAlgos)
RcppAlgos::permuteGeneral(4, 4, TRUE)
Upvotes: 4