Is there an R function to get the number of permutations of n objects take k P(n,k)?
Asked Answered
D

5

10

..or do I have to give

P.nk <- factorial(n) / factorial(n-k)

or

P.nk <- choose(n,k) * factorial(k)

Thank you.

Daedalus answered 20/5, 2010 at 7:30 Comment(2)
As others have said, there is a straight permutations function in gregmisc (gtools in the new parsed gregmisc packages). But, that and all other package functions I've found are really for generating permutations, not for just giving the total number of permutations. Therefore, they tend to be slow. I've benchmarked just such functions before. Your option 2 here is far and away the fastest, much faster than any package functions I've found. It also has a higher upper limit for calculations than your first option.Discretion
Thanks for the useful informationDaedalus
S
12

I don't know of any existing function. Your first suggestion will fail with large n. Your second idea should work fine when written as a function:

perm <- function(n,k){choose(n,k) * factorial(k)}

Then perm(500,2) will give 249500 for example.

Safire answered 20/5, 2010 at 9:4 Comment(1)
First suggestion could be rewrite as exp(lfactorial(n) - lfactorial(n-k)). But I will use second too.Bywoods
S
3

I think the gregmisc package provides these functions.

library(gregmisc)
permutations(n=4,r=4)

Mailing list reference: [R] permutation

Scholasticism answered 20/5, 2010 at 9:9 Comment(2)
Actually, what is asked would be given by: dim(permutations(n,k))[1]Mafia
package ‘gregmisc’ is not available (for R version 3.5.3) Jun 4, 2019Assiduity
I
2

Check out nsamp(n,k,ordered=T) in the 'prob' package

Isocline answered 20/5, 2010 at 9:20 Comment(2)
nsamp(500,2,ordered=TRUE) encounter problem state in Rob answer (value out of range).Bywoods
> nsamp(173,2,ordered=TRUE) [1] NaN Warning messages: 1: In factorial(n[i]) : value out of range in 'gammafn' 2: In factorial(n[i] - k[i]) : value out of range in 'gammafn' > nsamp(171,2,ordered=TRUE) [1] Inf Warning message: In factorial(n[i]) : value out of range in 'gammafn' > nsamp(170,2,ordered=TRUE) [1] 28730 ----R version 3.5.3Assiduity
R
1

Another way for doing that, from Base R is

permn <- prod( (n-(0:(k-1)))

that is a simple implementation of the following formula

$$p(n,k) = \prod_{j=0}^{k-1} n-j$$

Revenue answered 23/3, 2022 at 12:37 Comment(0)
A
0

package gtools

# R version 3.5.3
install.packages("gtools")
library(gtools)

base::nrow(gtools::permutations(500,2))

result:

[1] 249500

also see combinations-and-permutations-in-r, permutation_with_replacement.R

another package prob:

base::ncol(prob::permsn(500,2))

[1] 249500

Assiduity answered 4/6, 2019 at 3:6 Comment(1)
these options are really for generating permutations so will be really slow if all you need is the number of permutationsRiess

© 2022 - 2024 — McMap. All rights reserved.