Check numeric vector
Is a given object a numeric vector? This can be checked in three ways as follows:
### x is a numeric vector
x <- 1:3
check_numeric_vector(x)
#> [1] TRUE
test_numeric_vector(x)
#> [1] TRUE
assert_numeric_vector(x)
### y is not a numeric vector
y <- c(1, 2, "3")
check_numeric_vector(y)
#> [1] "Must be of type 'numeric', not 'character'"
test_numeric_vector(y)
#> [1] FALSE
assert_numeric_vector(y)
#> Error in eval(expr, envir, enclos): Assertion on 'y' failed: Must be of type 'numeric', not 'character'.
Check probability vector
A probability vector is a special type of numeric vector:
### p1 is a probability vector
p1 <- c(0.2, 0.3, 0.5)
check_probability_vector(p1)
#> [1] TRUE
test_probability_vector(p1)
#> [1] TRUE
assert_probability_vector(p1)
### p2 is not a probability vector
p2 <- c(0.2, 0.3, 0.6)
check_probability_vector(p2)
#> [1] "Must add up to 1"
test_probability_vector(p2)
#> [1] FALSE
assert_probability_vector(p2)
#> Error in eval(expr, envir, enclos): Assertion on 'p2' failed: Must add up to 1.
Split a vector into chunks
x <- 1:12
chunk_vector(x, n = 3, type = 1)
#> $`1`
#> [1] 1 2 3 4
#>
#> $`2`
#> [1] 5 6 7 8
#>
#> $`3`
#> [1] 9 10 11 12
chunk_vector(x, n = 3, type = 2)
#> $`1`
#> [1] 1 2 3
#>
#> $`2`
#> [1] 4 5 6
#>
#> $`3`
#> [1] 7 8 9
#>
#> $`4`
#> [1] 10 11 12
try(chunk_vector(x, n = 5, strict = TRUE))
#> Error : Input `n` is bad: Not a multiple of 'length(x)'
Generate vector subsets
The subsets()
function generates subsets of a
vector.
v <- month.name[1:3]
### all subsets
subsets(v)
#> [[1]]
#> [1] "January"
#>
#> [[2]]
#> [1] "February"
#>
#> [[3]]
#> [1] "March"
#>
#> [[4]]
#> [1] "January" "February"
#>
#> [[5]]
#> [1] "January" "March"
#>
#> [[6]]
#> [1] "February" "March"
#>
#> [[7]]
#> [1] "January" "February" "March"
### only subsets of length 1 or 3
subsets(v, c(1, 3))
#> [[1]]
#> [1] "January"
#>
#> [[2]]
#> [1] "February"
#>
#> [[3]]
#> [1] "March"
#>
#> [[4]]
#> [1] "January" "February" "March"
### the trivial case also works
subsets(integer())
#> list()