This function generates the compositions of an non-negative interger n into k parts or parts of any sizes. The results are in lexicographical or reversed lexicographical order.

compositions(n, k = NULL, descending = FALSE, layout = NULL,
  nitem = -1L, skip = NULL, index = NULL, nsample = NULL,
  drop = NULL)

Arguments

n

an non-negative integer to be partitioned

k

number of parts

descending

an logical to use reversed lexicographical order

layout

if "row", "column" or "list" is specified, the returned value would be a "row-major" matrix, a "column-major" matrix or a list respectively

nitem

number of compositions required, usually used with skip

skip

the number of compositions skipped

index

a vector of indices of the desired compositions

nsample

sampling random compositions

drop

vectorize a matrix or unlist a list

See also

icompositions for iterating compositions and ncompositions to calculate number of compositions

Examples

# all compositions of 4 compositions(4)
#> [,1] [,2] [,3] [,4] #> [1,] 1 1 1 1 #> [2,] 1 1 2 0 #> [3,] 1 2 1 0 #> [4,] 1 3 0 0 #> [5,] 2 1 1 0 #> [6,] 2 2 0 0 #> [7,] 3 1 0 0 #> [8,] 4 0 0 0
# reversed lexicographical order compositions(4, descending = TRUE)
#> [,1] [,2] [,3] [,4] #> [1,] 4 0 0 0 #> [2,] 3 1 0 0 #> [3,] 2 2 0 0 #> [4,] 2 1 1 0 #> [5,] 1 3 0 0 #> [6,] 1 2 1 0 #> [7,] 1 1 2 0 #> [8,] 1 1 1 1
# fixed number of parts compositions(6, 3)
#> [,1] [,2] [,3] #> [1,] 1 1 4 #> [2,] 1 2 3 #> [3,] 1 3 2 #> [4,] 1 4 1 #> [5,] 2 1 3 #> [6,] 2 2 2 #> [7,] 2 3 1 #> [8,] 3 1 2 #> [9,] 3 2 1 #> [10,] 4 1 1
# reversed lexicographical order compositions(6, 3, descending = TRUE)
#> [,1] [,2] [,3] #> [1,] 4 1 1 #> [2,] 3 2 1 #> [3,] 3 1 2 #> [4,] 2 3 1 #> [5,] 2 2 2 #> [6,] 2 1 3 #> [7,] 1 4 1 #> [8,] 1 3 2 #> [9,] 1 2 3 #> [10,] 1 1 4
# column major compositions(4, layout = "column")
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] #> [1,] 1 1 1 1 2 2 3 4 #> [2,] 1 1 2 3 1 2 1 0 #> [3,] 1 2 1 0 1 0 0 0 #> [4,] 1 0 0 0 0 0 0 0
compositions(6, 3, layout = "column")
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] #> [1,] 1 1 1 1 2 2 2 3 3 4 #> [2,] 1 2 3 4 1 2 3 1 2 1 #> [3,] 4 3 2 1 3 2 1 2 1 1
# list output compositions(4, layout = "list")
#> [[1]] #> [1] 1 1 1 1 #> #> [[2]] #> [1] 1 1 2 #> #> [[3]] #> [1] 1 2 1 #> #> [[4]] #> [1] 1 3 #> #> [[5]] #> [1] 2 1 1 #> #> [[6]] #> [1] 2 2 #> #> [[7]] #> [1] 3 1 #> #> [[8]] #> [1] 4 #>
compositions(6, 3, layout = "list")
#> [[1]] #> [1] 1 1 4 #> #> [[2]] #> [1] 1 2 3 #> #> [[3]] #> [1] 1 3 2 #> #> [[4]] #> [1] 1 4 1 #> #> [[5]] #> [1] 2 1 3 #> #> [[6]] #> [1] 2 2 2 #> #> [[7]] #> [1] 2 3 1 #> #> [[8]] #> [1] 3 1 2 #> #> [[9]] #> [1] 3 2 1 #> #> [[10]] #> [1] 4 1 1 #>
# zero sized compositions dim(compositions(0))
#> [1] 1 0
dim(compositions(5, 0))
#> [1] 0 0
dim(compositions(5, 6))
#> [1] 0 6
dim(compositions(0, 0))
#> [1] 1 0
dim(compositions(0, 1))
#> [1] 0 1