How to calculate combination and permutation in R?
Solution 1
You can use the combinat
package with R 2.13:
install.packages("combinat")
require(combinat)
permn(3)
combn(3, 2)
If you want to know the number of combination/permutations, then check the size of the result, e.g.:
length(permn(3))
dim(combn(3,2))[2]
Solution 2
The function combn is in the standard utils package (i.e. already installed)
choose is also already available in the Special {base}
Solution 3
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
Solution 4
The Combinations
package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use
install.packages("Combinations", repos = "http://www.omegahat.org/R")
See the documentation at http://www.omegahat.org/Combinations/
Solution 5
It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.
Comments
-
Maxim Veksler about 3 years
How one can calculate the number of combinations and permutations in R?
The Combinations package failed to install on Linux with the following message:
> install.packages("Combinations") Installing package(s) into ‘/home/maxim/R/x86_64-pc-linux-gnu-library/2.13’ (as ‘lib’ is unspecified) Warning message: In getDependencies(pkgs, dependencies, available, lib) : package ‘Combinations’ is not available (for R version 2.13.1)
-
Maxim Veksler over 12 yearsIs there something that could just give me a number of possible combinations, rather then printing them all?
-
Maxim Veksler over 12 yearsThis also does not work, I think that the R version I'm using is (2.13) is not compatible
-
Brian Diggs over 12 yearsAh, there was a typo; it should be omegahat, not omeghat. I copied and pasted the command, but I should have tested it first. I've updated my answer. This updated code works for me in 2.13.2 on Windows.
-
chl about 12 years@MaximVeksler Take a look at
choose
. (choose(5, 2) == ncol(combn(5, 2))
) -
bubakazouba over 8 yearswow alot of hassle for a simple question that its answer was 3 words "the choose function"
-
Asif Iqbal almost 8 yearsThis site can be used as alternate: englishact.com/Permutation/index.php
-
Marius Hofert over 6 yearsThat's a bad idea numerically. R can evaluate
choose(500, 2)
but notfactorial(500)
. You should at least work withlfactorial
and then takeexp()
. The only reason I'm posting this is that your answer has so many upvotes, it seems people don't know these things... -
agent18 about 5 yearschoose(n,k) = nCk