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:
Say we want to split a vector into three chunks of equal size:
Alternatively, we can split x
into chunks of size
n = 3
by setting type = 2
:
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
:
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