Skip to contents

This function calculates combinations of a set of objects. It offers flexibility in allowing for combinations with repetition, as well as returning counts of corresponding permutations. It also provides different output formats tailored for further processing or analysis.

Usage

combinations(
  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 combination.

v

A vector or list containing the objects to be combined. 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 combinations 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 permutations corresponding to each combination.

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 combinations as a matrix, dataframe, tibble, or datatable. If `count.permutations` is TRUE, the last column of the output will indicate the number of permutations corresponding to each combination.

Examples

# Basic combination without repetition
combinations(n = 4, r = 2)
#>      V1 V2
#> [1,]  1  2
#> [2,]  1  3
#> [3,]  1  4
#> [4,]  2  3
#> [5,]  2  4
#> [6,]  3  4

# Combination with repetition
combinations(n = 4, r = 2, repeats.allowed = TRUE)
#>       V1 V2
#>  [1,]  1  1
#>  [2,]  1  2
#>  [3,]  1  3
#>  [4,]  1  4
#>  [5,]  2  2
#>  [6,]  2  3
#>  [7,]  2  4
#>  [8,]  3  3
#>  [9,]  3  4
#> [10,]  4  4

# Combination with repetition and count of corresponding permutations
combinations(n = 4, r = 2, repeats.allowed = TRUE, count.permutations = TRUE)
#>       V1 V2 n_permutations
#>  [1,]  1  1              2
#>  [2,]  1  2              1
#>  [3,]  1  3              1
#>  [4,]  1  4              1
#>  [5,]  2  2              2
#>  [6,]  2  3              1
#>  [7,]  2  4              1
#>  [8,]  3  3              2
#>  [9,]  3  4              1
#> [10,]  4  4              2

# Using a custom vector of objects for combinations
combinations(v = c("apple", "banana", "cherry"), r = 2)
#>      V1       V2      
#> [1,] "apple"  "banana"
#> [2,] "apple"  "cherry"
#> [3,] "banana" "cherry"