Permutations in R

[This article was first published on R – Predictive Hacks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

During the interview process for Data Science positions, it is likely to be asked to calculate Combinations or Permutations. Today we will provide an example of how we can solve numerically permutation problems in R.


Find all Permutations of the word baboon

Mathematically we can approach this question as follows:

\(P=\frac{n!}{n_1! n_2! n_3!…n_k!}\)

Where:

  • \(n\) is the total number of object, i.e. letters in our case which is 6
  • \(n_1\) is the number of objects of type 1, for example, the number of b which is 2
  • \(n_2\) is the number of objects of type 2, for example, the number of a which is 1
  • \(n_3\) is the number of objects of type 3, for example, the number of o which is 2
  • \(n_4\) is the number of objects of type 4, for example, the number of n which is 1

Hence the number of permutations is \(P=\frac{6!}{2! \times 2!} = 180\)


Return all Permutations in R

Let’s return all permutations in R

Working with combinat package

library(combinat)
# get the list of all permutations
my_list<-combinat::permn(c("b","a","b","o","o","n"))

# convert the list to a matrix
my_matrix<-do.call(rbind,my_list)

#take the unique rows
my_matrix<-unique(my_matrix)

head(my_matrix)
 

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "b"  "a"  "b"  "o"  "o"  "n" 
[2,] "b"  "a"  "b"  "o"  "n"  "o" 
[3,] "b"  "a"  "b"  "n"  "o"  "o" 
[4,] "b"  "a"  "n"  "b"  "o"  "o" 
[5,] "b"  "n"  "a"  "b"  "o"  "o" 
[6,] "n"  "b"  "a"  "b"  "o"  "o" 

If we want to get the number of rows of the table, which are actually our permutations:

dim(my_matrix)
# [1] 180   6

As expected we got 180 rows (the permutations) and 6 columns (the number of letters)


Comments

When we are in a position to get all the possible permutations, we will be able to calculate the permutations of more complicated problems. Let’s say, that the question was to calculate all the possible permutations of the word baboon but by picking 4 letters each time (instead of 6).

To leave a comment for the author, please follow the link and comment on their blog: R – Predictive Hacks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)