This questions was asked previously but only for vectors with non-repeating elements. I was not able to find an easy solution to get all combinations from a vector with repeating elements. To illustrate I listed an example below.
x <- c('red', 'blue', 'green', 'red', 'green', 'red')
Vector x has 3 repeating elements for 'red' and 2 for 'green'. The expected outcome for all unique combinations would be like this.
# unique combinations with one element
'red'
'blue'
'green'
# unique combination with two elements
'red', 'blue' # same as 'blue','red'
'red', 'green'
'red', 'red'
'blue', 'green'
'green', 'green'
# unique combination with three elements
'red', 'blue', 'green'
'red', 'red', 'blue'
'red', 'red', 'green'
'red', 'red', 'red' # This is valid because there are three 'red's
'green', 'green', 'red'
'green', 'green', 'blue'
# more unique combinations with four, five, and six elements
Use
combn()
withlapply()
should do the trick.All unique combinations
Although strictly speaking those aren't all unique combinations, as some of them are permutations of each other.
Properly unique combinations
If you don't want to manually enter the frequencies:
Or using
RcppAlgos
: