# R Functions Related to Counting and Probability

### Installing and Loading the "gtools" Package

For some of the functions below to work, you will have to install the "gtools" package. Installation is easy -- just start up RStudio, and then in the R Console, type the following:

> install.packages("gtools")

You only ever need to install a package once; thereafter it will be available for your R installation.
Once installed, you can load your installed package with

> library(gtools)

### The Functions

`factorial()`

Returns $x! = x(x-1)(x-2) \cdots 3 \cdot 2 \cdot 1$. For example, $5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120$ can be found with

> factorial(5)
[1] 120

`choose()`

Returns ${}_n C_k$, the number of combinations of $n$ elements taken $k$ at a time. For example, ${}_5 C_3 = 10$ can be found with

> choose(5,3)
[1] 10

Note that ${}_n P_k$, the number of permutations of $n$ elements taken $k$ at a time can be calculated from ${}_n C_k$ as
$${}_n P_k = k! \cdot ({}_n C_k)$$
As an example, ${}_4 P_3 = 3! \cdot ({}_4 C_3) = 24$ can be found with
> factorial(3)*choose(4,3)
[1] 24

`combinations()`

(requires the "gtools" package)

Generate all combinations of $n$ elements (of a given vector) taken $k$ at a time. Be aware, the number of possible combinations grows *very* quickly as $n$ increases. For example, to find all combinations of the $5$ elements taken $3$ at a time from $\{1,2,3,4,5\}$, where each row in the resulting matrix is a different combination:

> combinations(5,3,1:5)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 2 5
[4,] 1 3 4
[5,] 1 3 5
[6,] 1 4 5
[7,] 2 3 4
[8,] 2 3 5
[9,] 2 4 5
[10,] 3 4 5

`permutations()`

(requires the "gtools" package)

Generate all permutations of $n$ elements (of a given vector) taken $k$ at a time. Be aware, the number of possible permutations grows *very* quickly as $n$ increases. For example, to find all permutations of the $4$ elements taken $3$ at a time from $\{1,2,3,4\}$, where each row in the resulting matrix is a different permutation:

> permutations(4,3,1:4)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 3 2
[4,] 1 3 4
[5,] 1 4 2
[6,] 1 4 3
[7,] 2 1 3
[8,] 2 1 4
[9,] 2 3 1
[10,] 2 3 4
[11,] 2 4 1
[12,] 2 4 3
[13,] 3 1 2
[14,] 3 1 4
[15,] 3 2 1
[16,] 3 2 4
[17,] 3 4 1
[18,] 3 4 2
[19,] 4 1 2
[20,] 4 1 3
[21,] 4 2 1
[22,] 4 2 3
[23,] 4 3 1
[24,] 4 3 2