How to compute combinations & permutations in R?

In R, the n choose k operation can be used to compute combinations and permutations. This operation can be invoked using the choose() function, which takes two arguments (n and k) and returns the number of combinations and permutations of the two arguments. To compute combinations and permutations, the arguments n and k are entered in the choose() function, and the result is returned. For example, the combination and permutation of 4 and 2 can be computed using the choose(4,2) function in R, which returns the result 6.


You can use the following functions to calculate combinations and permutations in R:

#calculate total combinations of size r from n total objects
choose(n, r)

#calculate total permutations of size r from n total objects
choose(n, r) * factorial(r)

The following examples show how to use each of these functions in practice.

Example 1: Calculate Total Combinations

Combinations represent ways of selecting a sample from a group of objects in which the order of the objects does not matter.

For example, suppose we have a bag of four marbles: red, blue, green, and yellow. Suppose we’d like to select two marbles randomly from the bag, without replacement.

Here are the different combinations of marbles we could select:

  • {red, blue}
  • {red, green}
  • {red, yellow}
  • {blue, green}
  • {blue, yellow}
  • {green, yellow}

There are 6 total combinations.

Here is how to calculate the total number of combinations in R:

#calculate total combinations of size 2 from 4 total objects
choose(4, 2)

[1] 6

Our answer matches the number of combinations that we calculated by hand.

Example 2: Calculate Total Permutations

Permutations represent ways of selecting a sample from a group of objects in which the order of the objects does matter.

For example, suppose we have a bag of four marbles: red, blue, green, and yellow.

Suppose we’d like to select two marbles randomly from the bag, without replacement.

Here are the different permutations of marbles we could select:

  • {red, blue}, {blue, red}
  • {red, green}, {green, red}
  • {red, yellow}, {yellow, red}
  • {blue, green}, {green, blue}
  • {blue, yellow}, {yellow, blue}
  • {green, yellow}, {yellow, green}

There are 12 total permutations.

Here is how to calculate the total number of permutations in R:

#calculate total permutations of size 2 from 4 total objects
choose(4, 2) * factorial(2)

[1] 12

Our answer matches the number of permutations that we calculated by hand.

The following tutorials explain how to perform other common tasks in R:

How to Replicate Rows in Data Frame in R

x