# Calculate Combinations & Permutations in R (4 Examples)

In this R tutorial youâ€™ll learn how to generate and count all possible permutations and combinations of the elements in a vector.

The tutorial will contain the following information:

Before we jump into the examples, we need to install and load the combinat package:

```install.packages("combinat")                   # Install combinat package

So now the part you have been waiting for â€“ the exemplifying R syntax.

## Example 1: Create List Containing All Possible Permutations

The following R programming code shows how to generate a list of all possible permutations in R.

For this, we can apply the permn function that is provided by the combinat package:

```permut <- permn(3)                             # Create list of permutations
permut                                         # Print list of permutations
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 1 3 2
#
# [[3]]
# [1] 3 1 2
#
# [[4]]
# [1] 3 2 1
#
# [[5]]
# [1] 2 3 1
#
# [[6]]
# [1] 2 1 3```

The previous output of the RStudio console shows a list that contains all possible permutations of the values 1, 2, and 3.

## Example 2: Count Number of Possible Permutations

Example 2 illustrates how to get the number of possible permutations of a vector object.

For this, we can use the length function in combination with the permn function:

```permut_count <- length(permn(3))               # Count permutations
permut_count                                   # Print count of permutations
# [1] 6```

There exist six possible permutations of the values 1, 2, and 3.

## Example 3: Create Matrix Containing All Possible Combinations

In Example 3, Iâ€™ll illustrate how to create a matrix of all possible combinations with a particular length of a vector of values.

For this, we can use the combn function of the combinat package.

Note that the combn function is also provided by the utils package, which is part of Base R. However, in this example we are using the combn function of combinat:

```combi <- combinat::combn(3, 2)                 # Create matrix of combinations
combi                                          # Print matrix of combinations```

The previous matrix illustrates all possible combinations with a length of two of the values 1, 2, and 3.

## Example 4: Count Number of Possible Combinations

Example 4 illustrates how to count the number of possible combinations.

For this, we can apply the ncol function together with the combn function:

```combi_count <- ncol(combinat::combn(3, 2))     # Count combinations
combi_count                                    # Print count of combinations
# [1] 3```

As you can see, there exist three possible combinations.

## Video & Further Resources

Would you like to know more about combinations and permutations? Then I can recommend having a look at the following video of my YouTube channel. In the video, I show the R codes of this tutorial.

This article showed how to calculate permutations and combinations in the R programming language. In case you have any further questions, please let me know in the comments.

Subscribe to the Statistics Globe Newsletter

• LUCA ZENERE
April 8, 2021 6:01 pm

Useful!
PS: in picture Table 1, you should show rows as [1,] and [2,] not as [,1] and [,2]. that is to say:
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 3 3
thank you joachim!

• Wow, thank you so much for pointing on this mistake Luca! Seems like I have done this wrong in many of my previous tutorials…

I’m afraid I will not be able to change this for the old tutorials, but I have just fixed my code for the creation of table images and in the future it should not happen again:

Thanks again for helping me to improve my tutorials!

Joachim

• Francesca Murdocco
November 29, 2021 2:33 pm

Hi,

I am a phd student in work psychology.
for the purpose of my phd I am developing a scale which requires me to match my items by Social desirability levels, to do so I have to find all the possible combinations of 2 of my questions with the combn() function and calculate the indexes with another package. The authors of the reference paper for this technique, provided the R script for this purpose, but for some reason my code stops with an error message for the combn()… I have been trying to solve it for now a week and I am quite desperate at this point!!

This is my code:

IIA<-function(path,file){
setwd(path)
require(combinat)
library(irrCAC)
Combinations <-combinat::combn(ncol(x = "DATA"), 2, simplify = FALSE)
itempair=c(rep(NA,ncol(Combinations)))
D=c(rep(NA,ncol(Combinations)))
BPlin=c(rep(NA,ncol(Combinations)))
BPlinCI=c(rep(NA,ncol(Combinations)))
AClin=c(rep(NA,ncol(Combinations)))
AClinCI=c(rep(NA,ncol(Combinations)))
for(i in 1:ncol(Combinations)){
SelectItem <- Combinations[ , i]
itempair[i]=paste0(SelectItem [1],"&", SelectItem [2])

D[i]=abs(mean(DATA[ , SelectItem][,2])-mean(DATA[, SelectItem][,1]))
BPlin[i]=bp.coeff.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "linear")\$est[,4]
BPlinCI[i]=bp.coeff.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "linear")\$est[,6]
AClin[i]=gwet.ac1.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "linear")\$est[,4]
AClinCI[i]=gwet.ac1.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "linear")\$est[,6]
}
write.table(result, "estimates.csv",col.names=TRUE,row.names=FALSE, sep = ",")
}

And this is the error message:

Error in combinat::combn(ncol(x = "DATA"), 2, simplify = FALSE) : n < m

I cannot see the issue anywhere….Could you help ? or tell me where I can find more help/material on the package/function?

Francesca

• Hi Francesca,

It is difficult to reproduce this error without seeing the actual data.

Could you send (a subset of) your data to my email joachim@statisticsglobe.com ? I can have a look at it.

Regards,
Joachim

• Hussein Eledum
January 25, 2022 4:35 pm

Respected Sir,

The following code produces NULL while the correct answer is 1

comb_count=ncol(combinat::combn(2,2))

• Hey Hussein,

Thanks for the hint!

This is actually a special case, because the combn function does not return a matrix when there’s only one possible combination.

To get a solution for this special case as well, you may use the following code:

`ncol(as.matrix(combinat::combn(2,2)))`

Regards,
Joachim

• Jeffrey Evans
August 30, 2023 4:09 pm

Why not stay with base, and avoid loading a package into the global namespace, and use something like;

( x <- paste0("class", 1:5) )
expand.grid(x, x)

# Or, with expansion. Same as expand.grid but, without
# duplicates or self matching obs
( idx <- lapply(2:length(x), function(y) {
utils::combn(x, y, simplify = FALSE)
}) )
idx[[1]]