Permutations and combinations in R

Before digging into permutations and combinations in R using iteration, I invite you to read my first post. Indeed, I have already:

  • covered the difference between permutations (order matters) and combinations (order doesn’t matter)
  • shown an example
  • counted the number of permutations and combinations
  • and implemented the formulas in R

So, permutations and combinations can be generated using iteration or recursion. An iteration is a loop in which we repeat instructions, while a recursion is a function that calls itself to repeat instructions.

In the next sections, we will use r loops to enumerate all the possible subsets of r elements from a given set of n elements in base R. But instead of working directly on the subsets, you can of course store them in a data frame.

cheat sheet of the permutations and combinations in R using iteration
Cheat sheet of the permutations and combinations in R using iteration

Variables assignment

cells = c("neutrophils", "monocytes", "lymphocytes", "eosinophils", "basophils")
n = length(cells)

Permutations with repetition

r = 2

for (i in 1:n){
  for (j in 1:n){
    print(paste(cells[i], cells[j], sep = "-"))
  }
}

r = 3

for (i in 1:n){
  for (j in 1:n){
    for (k in 1:n){
      print(paste(cells[i], cells[j], cells[k], sep = "-"))
    }
  }
}

Permutations without repetition

r = 2

for (i in 1:n){
  for (j in setdiff(1:n, i)){
    print(paste(cells[i], cells[j], sep = "-"))
  }
}

r = 3

for (i in 1:n){
  for (j in setdiff(1:n, i)){
    for (k in setdiff(1:n, c(i, j))){
      print(paste(cells[i], cells[j], cells[k], sep = "-"))
    }
  }
}

Combinations with repetition

r = 2

for (i in 1:n){
  for (j in i:n){
    print(paste(cells[i], cells[j], sep = "-"))
  }
}

r = 3

for (i in 1:n){
  for (j in i:n){
    for (k in j:n){
      print(paste(cells[i], cells[j], cells[k], sep = "-"))
    }
  }
}

Combinations without repetition

r = 2

for (i in 1:n){
  for (j in setdiff(i:n, i)){
    print(paste(cells[i], cells[j], sep = "-"))
  }
}

r = 3

for (i in 1:n){
  for (j in setdiff(i:n, i)){
    for (k in setdiff(j:n, c(i, j))){
      print(paste(cells[i], cells[j], cells[k], sep = "-"))
    }
  }
}

Conclusion

To sum up, the implementation of the four cases is quite easy in R. Until now, I only had to generate pairs of items without order and without repetition. And you?

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply