How to Generate Combinations in R

05.06.2021

Generating combinations is a common task when building websties and programs. In this article, we wil learn how to generate combinations in R.

To generate combinations in R, we can use the conbn method which will generate all possible groups of k from n items. The signature of the method looks like cobn(items, k).

If we would like to generate all combnations of groups of 3 from the numbers 1-4, we can do the following:

combn(1:4, 3)

#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    2
# [2,]    2    2    3    3
# [3,]    3    4    4    4

Each column in the output is a distinct group.

Now, we can do the same with string combinations using the following.

strings = c("A", "B", "C", "D")
combn(strings, 3)

#      [,1] [,2] [,3] [,4]
# [1,] "A"  "A"  "A"  "B" 
# [2,] "B"  "B"  "C"  "C" 
# [3,] "C"  "D"  "D"  "D"