Helpers for working with vectors

Generate vector subsets

Say we want to generate all subsets of a vector:

v <- 1:4
subsets(v)
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 3
#> 
#> [[4]]
#> [1] 4
#> 
#> [[5]]
#> [1] 1 2
#> 
#> [[6]]
#> [1] 1 3
#> 
#> [[7]]
#> [1] 1 4
#> 
#> [[8]]
#> [1] 2 3
#> 
#> [[9]]
#> [1] 2 4
#> 
#> [[10]]
#> [1] 3 4
#> 
#> [[11]]
#> [1] 1 2 3
#> 
#> [[12]]
#> [1] 1 2 4
#> 
#> [[13]]
#> [1] 1 3 4
#> 
#> [[14]]
#> [1] 2 3 4
#> 
#> [[15]]
#> [1] 1 2 3 4

It is also possible to only generate the subsets of, say, size 2 and 3:

v <- 1:4
subsets(v, n = 2:3)
#> [[1]]
#> [1] 1 2
#> 
#> [[2]]
#> [1] 1 3
#> 
#> [[3]]
#> [1] 1 4
#> 
#> [[4]]
#> [1] 2 3
#> 
#> [[5]]
#> [1] 2 4
#> 
#> [[6]]
#> [1] 3 4
#> 
#> [[7]]
#> [1] 1 2 3
#> 
#> [[8]]
#> [1] 1 2 4
#> 
#> [[9]]
#> [1] 1 3 4
#> 
#> [[10]]
#> [1] 2 3 4

Split vector into chunks

Say we want to split a vector into three chunks of equal size:

x <- 1:6
chunk_vector(x, n = 3)
#> $`1`
#> [1] 1 2
#> 
#> $`2`
#> [1] 3 4
#> 
#> $`3`
#> [1] 5 6

Alternatively, we can split x into chunks of size n = 3 by setting type = 2:

chunk_vector(x, n = 3, type = 2)
#> $`1`
#> [1] 1 2 3
#> 
#> $`2`
#> [1] 4 5 6

Both somehow also works if n is not a multiple of length(x):

x <- 1:7
chunk_vector(x, n = 3)
#> $`1`
#> [1] 1 2 3
#> 
#> $`2`
#> [1] 4 5
#> 
#> $`3`
#> [1] 6 7
chunk_vector(x, n = 3, type = 2)
#> $`1`
#> [1] 1 2 3
#> 
#> $`2`
#> [1] 4 5 6
#> 
#> $`3`
#> [1] 7

To prevent such “odd” cases, set strict = TRUE:

try(chunk_vector(1:7, n = 3, strict = TRUE))
#> Error in chunk_vector(1:7, n = 3, strict = TRUE) : 
#>   'n' is not a multiple of 'length(x)'

Find the indices of first or last occurrence of unique vector elements

Say we want to find the positions of first or last occurrence of the unique elements of the following vector:

x <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
vector_occurrence(x, "first")
#> [1] 1 4 7
vector_occurrence(x, "last")
#> [1] 3 6 9

The returned positions correspond to

unique(x)
#> [1] 1 2 3