Compute Permutations of Elements
permutations.RdThis function calculates permutations of a set of objects. It offers flexibility in allowing for permutations with repetition, as well as returning counts of identical permutations. It also provides different output formats tailored for further processing or analysis.
Usage
permutations(
n = NULL,
r,
v = NULL,
set = TRUE,
repeats.allowed = FALSE,
count.permutations = FALSE,
out_format = "auto"
)Arguments
- n
Numeric. The number of elements in the input set. If `v` is provided, `n` is ignored.
- r
Numeric. The number of elements selected for each permutation.
- v
A vector or list containing the objects to be permuted. If not specified, it defaults to a sequence from 1 to `n`.
- set
Logical. If TRUE, the function will remove duplicate values from the input vector `v`.
- repeats.allowed
Logical. Determines whether permutations with repetition are allowed. Default is FALSE.
- count.permutations
Logical. If set to TRUE, an additional column will be appended to the output indicating the number of identical permutations for each row.
- out_format
A character string specifying the desired format for the output. Valid options are "matrix", "dataframe", "tibble", "datatable", or "auto". If "auto" is chosen, the function will decide the most suitable format based on other input parameters.
Value
Depending on the `out_format` specified, the function returns permutations as a matrix, dataframe, tibble, or datatable. If `count.permutations` is TRUE, the last column of the output will indicate the number of identical permutations for each permutation.
Examples
# Basic permutation without repetition
permutations(n = 4, r = 2)
#> V1 V2
#> [1,] 1 2
#> [2,] 2 1
#> [3,] 1 3
#> [4,] 3 1
#> [5,] 1 4
#> [6,] 4 1
#> [7,] 2 3
#> [8,] 3 2
#> [9,] 2 4
#> [10,] 4 2
#> [11,] 3 4
#> [12,] 4 3
# Permutation with repetition
permutations(n = 4, r = 2, repeats.allowed = TRUE)
#> V1 V2
#> [1,] 1 1
#> [2,] 1 2
#> [3,] 1 3
#> [4,] 1 4
#> [5,] 2 1
#> [6,] 2 2
#> [7,] 2 3
#> [8,] 2 4
#> [9,] 3 1
#> [10,] 3 2
#> [11,] 3 3
#> [12,] 3 4
#> [13,] 4 1
#> [14,] 4 2
#> [15,] 4 3
#> [16,] 4 4
# Permutation with repetition and count of identical permutations
permutations(n = 4, r = 2, repeats.allowed = TRUE, count.permutations = TRUE)
#> V1 V2 n_permutations
#> [1,] 1 1 2
#> [2,] 2 1 1
#> [3,] 3 1 1
#> [4,] 4 1 1
#> [5,] 1 2 1
#> [6,] 2 2 2
#> [7,] 3 2 1
#> [8,] 4 2 1
#> [9,] 1 3 1
#> [10,] 2 3 1
#> [11,] 3 3 2
#> [12,] 4 3 1
#> [13,] 1 4 1
#> [14,] 2 4 1
#> [15,] 3 4 1
#> [16,] 4 4 2
# Using a custom vector of objects for permutations
permutations(v = c("apple", "banana", "cherry"), r = 2)
#> V1 V2
#> [1,] "apple" "banana"
#> [2,] "banana" "apple"
#> [3,] "apple" "cherry"
#> [4,] "cherry" "apple"
#> [5,] "banana" "cherry"
#> [6,] "cherry" "banana"