library(assertive)
## assertive has some important changes. Read ?changes for details.
library(knitr)
opts_chunk$set(error = TRUE)
Before you begin, get to know your way around the assertive package. Take a look at ls("package:assertive")
and have a quick read of ?assertive
.
Consider the variable, x
:
x <- with(expand.grid(x = -1:1, y = -1:0), x / y)
Write a check that x
is a numeric vector.
# check for being numeric
assert_is_numeric(x)
Write a check that all the elements of x
are finite.
# check for being finite
assert_all_are_finite(x)
## Error in eval(expr, envir, enclos): x are not all finite.
## There were 3 failures:
## Position Value Cause
## 1 4 -Inf infinite
## 2 5 NaN not a number
## 3 6 Inf infinite
Write a check that all the elements of x
are not missing.
# check for having no missing values
assert_all_are_not_na(x)
## Error in eval(expr, envir, enclos): The values of x are sometimes NA.
## There was 1 failure:
## Position Value Cause
## 1 5 NaN missing
Consider the variable, y
:
y <- seq.int(-pi, 3 * pi, pi)
Write some checks that y
contains only numbers greater than or equal to zero, and less than two pi. (Be careful with boundary values.)
# checks for range here
assert_all_are_in_right_open_range(y, 0, 2 * pi)
## Error in eval(expr, envir, enclos): y are not all in the range [0,6.28318530717959).
## There were 3 failures:
## Position Value Cause
## 1 1 -3.14159265358979 too low
## 2 4 6.28318530717959 too high
## 3 5 9.42477796076938 too high
Consider the list variable, z
.
z <- list(a = rnbinom(10, 5, 0.5))
Is it a scalar object? Use is_scalar
with both metrics to see.
# checks for size here
is_scalar(z) # implicitly metric = "length"
## [1] TRUE
is_scalar(z, metric = "elements")
## [1] FALSE
## Cause of failure: z has 10 elements, not 1.