# 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 library("combinat") # Load 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.

**Please accept YouTube cookies to play this video.** By accepting you will be accessing content from YouTube, a service provided by an external third party.

If you accept this notice, your choice will be saved and the page will refresh.

In addition, you could read the related tutorials on statisticsglobe.com.

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.

### Statistics Globe Newsletter

## 8 Comments. Leave new

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

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)

DATA<- read.csv(file=file, header=FALSE, sep=",")

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)))

BPquad=c(rep(NA,ncol(Combinations)))

BPquadCI=c(rep(NA,ncol(Combinations)))

AClin=c(rep(NA,ncol(Combinations)))

AClinCI=c(rep(NA,ncol(Combinations)))

ACquad=c(rep(NA,ncol(Combinations)))

ACquadCI=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]

BPquad[i]=bp.coeff.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "quadratic")$est[,4]

BPquadCI[i]=bp.coeff.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "quadratic")$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]

ACquad[i]=gwet.ac1.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "quadratic")$est[,4]

ACquadCI[i]=gwet.ac1.raw(DATA.frame(DATA[ , SelectItem][,2],DATA[, SelectItem][,1]),weights = "quadratic")$est[,6]

}

result=data.frame(itempair,D,BPlin,BPlinCI,BPquad,BPquadCI,AClin,AClinCI,ACquad,ACquadCI)

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?

Thanks for your help in advance

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

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:

Regards,

Joachim

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]]

Hello Jeffrey,

For this specific example, the base R solution is quite elegant. If you’re only generating combinations of vectors once or twice in your code, there’s probably no need to load an external package. However, if you find yourself frequently needing more advanced combinatorics functionalities, it might make sense to use the combinat package or similar, as it can make your code cleaner and easier to understand in the long run. In general, the decision to use base R or external packages should be based on your specific needs, the complexity of the task, and your personal or team’s preferences.

Best,

Cansu