User0261
User0261

Reputation: 3

Using expand.grid function with n elements

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

Answers (2)

akrun
akrun

Reputation: 886948

We can replicate 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

Joseph Wood
Joseph Wood

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

Related Questions