how can i create a combinations of element with at most x repetitions for each one

Viewed 44

I would be generate a combinations of a vector x of 5 element with at most 2 repetitions for each element.

x = c(1,2,3,4,5,6,7,8,9,10)  

I'm using combn(x,5) but return the combination of 5 element without repetition.

In output I would be like : ((1,2,3,4,5), (1,2,3,4,6), ..., (1,1,3,4,5),(1,2,3,4,4), (1,1,2,2,3), ...)

Most important thing is that each element is represented at most twice. I would like to know if there is a function that can do this.

2 Answers

You are after combinations of multisets. There are a couple of libraries capable of producing the desired output without producing any duplicates combinations: arrangements and RcppAlgos, which I authored. Here is how you would use it:

arrangements::combinations(5, 5, freq = rep(2, 5))

RcppAlgos::comboGeneral(5, 5, freqs = rep(2, 5))

Note, the output from both libraries is in lexicographical order. Also, these libraries are written in compiled languages, so they extend well to larger cases.

You could just double the elements in x using rep. Designing your own vector like so gives you total control over the number of repetitions.

combn(x,5)
x <- rep(c(1:5),2)
> head(t(combn(x,5)))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    1
[3,]    1    2    3    4    2
[4,]    1    2    3    4    3
[5,]    1    2    3    4    4
[6,]    1    2    3    4    5

EDIT: as commented, this will generate duplicates, if this is not what you want, you could use unique(t(combn...))) to remove these duplicates.

Related