Generate Possible Combinations & Permutations in R (Example Code)

In this tutorial, I’ll show how to calculate permutations and combinations in R.

Example: Calculate Count of Permutations & Combinations

install.packages("combinat")       # Install combinat package
library("combinat")                # Load combinat
permn(4)                           # List of permutations
# [[1]]
# [1] 1 2 3 4
# 
# [[2]]
# [1] 1 2 4 3
# 
# [[3]]
# [1] 1 4 2 3
# 
# [[4]]
# [1] 4 1 2 3
# 
# [[5]]
# [1] 4 1 3 2
# 
# [[6]]
# [1] 1 4 3 2
# 
# [[7]]
# [1] 1 3 4 2
# 
# [[8]]
# [1] 1 3 2 4
# 
# [[9]]
# [1] 3 1 2 4
# 
# [[10]]
# [1] 3 1 4 2
# 
# [[11]]
# [1] 3 4 1 2
# 
# [[12]]
# [1] 4 3 1 2
# 
# [[13]]
# [1] 4 3 2 1
# 
# [[14]]
# [1] 3 4 2 1
# 
# [[15]]
# [1] 3 2 4 1
# 
# [[16]]
# [1] 3 2 1 4
# 
# [[17]]
# [1] 2 3 1 4
# 
# [[18]]
# [1] 2 3 4 1
# 
# [[19]]
# [1] 2 4 3 1
# 
# [[20]]
# [1] 4 2 3 1
# 
# [[21]]
# [1] 4 2 1 3
# 
# [[22]]
# [1] 2 4 1 3
# 
# [[23]]
# [1] 2 1 4 3
# 
# [[24]]
# [1] 2 1 3 4
length(permn(4))                   # Number of permutations
# [1] 24
combinat::combn(4, 3)              # Matrix of combinations
ncol(combinat::combn(4, 3))        # Number of combinations
# [1] 4

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top