Learn R Programming

gtools (version 3.9.5)

combinations: Enumerate the Combinations or Permutations of the Elements of a Vector

Description

combinations enumerates the possible combinations of a specified size from the elements of a vector. permutations enumerates the possible permutations.

Usage

combinations(n, r, v = 1:n, set = TRUE, repeats.allowed = FALSE)

permutations(n, r, v = 1:n, set = TRUE, repeats.allowed = FALSE)

Value

Returns a matrix where each row contains a vector of length r.

Arguments

n

Size of the source vector

r

Size of the target vectors

v

Source vector. Defaults to 1:n

set

Logical flag indicating whether duplicates should be removed from the source vector v. Defaults to TRUE.

repeats.allowed

Logical flag indicating whether the constructed vectors may include duplicated values. Defaults to FALSE.

Author

Original versions by Bill Venables Bill.Venables@cmis.csiro.au. Extended to handle repeats.allowed by Gregory R. Warnes greg@warnes.net.

Details

Caution: The number of combinations and permutations increases rapidly with n and r!.

To use values of n above about 45, you will need to increase R's recursion limit. See the expression argument to the options command for details on how to do this.

Taken from an email by Brian D Ripley <ripley@stats.ox.ac.uk> to r-help dated Tue, 14 Dec 1999 11:14:04 +0000 (GMT) in response to Alex Ahgarin datamanagement@email.com. Original version was named "subsets" and was Written by Bill Venables.

References

Venables, Bill. "Programmers Note", R-News, Vol 1/1, Jan. 2001. https://cran.r-project.org/doc/Rnews/

See Also

Examples

Run this code

combinations(3,2,letters[1:3])
combinations(3,2,letters[1:3],repeats=TRUE)

permutations(3,2,letters[1:3])
permutations(3,2,letters[1:3],repeats=TRUE)

if (FALSE) {
# To use large 'n', you need to change the default recusion limit
options(expressions=1e5)
cmat <- combinations(300,2)
dim(cmat) # 44850 by 2 
}

Run the code above in your browser using DataLab