/
check-n.R
89 lines (83 loc) · 1.88 KB
/
check-n.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#' @inherit check_string
#'
#' @title Check If Argument Is Single Natural Number
#'
#' @description Check if an argument is a single natural number,
#' and if not, generate an error message.
#'
#' Can be used to check indices, for example.
#'
#' @param zero Optional. `TRUE` or `FALSE` which indicates if zero is
#' acceptable. The default value is `FALSE`.
#'
#' @return `check_n()` returns an invisible `NULL` if the argument
#' is valid, or it generates an error message.
#'
#' `is_n()` returns `TRUE` or `FALSE`.
#'
#' @export
#'
#' @examples
#' x <- 1
#' check_n(x)
#'
#' x <- 1L
#' check_n(x)
#'
#' sapply(c(1, 2.1, 0, Inf, NA, -9), is_n)
#'
#' \dontrun{
#' # `x` must be a numeric
#' x <- "1"
#' check_n(x)
#'
#' # `x` must have length 1
#' x <- 1:2
#' check_n(x)
#'
#' # `x` must not be `NA`
#' x <- NA_integer_
#' check_n(x)
#'
#' # `x` must be larger than 0
#' x <- -1
#' check_n(x)
#'
#' # `x` must be an integer in a mathematical sense
#' x <- 1.1
#' check_n(x)
#'
#' # make `0` acceptable
#' x <- 0
#' check_n(x)
#' check_n(x, zero = TRUE)
#' }
check_n <- function(x, name = NULL, general = NULL, specific = NULL,
supplement = NULL, zero = FALSE, ...) {
if (is.null(name)) {
name <- deparse(substitute(x))
}
if (is.null(general)) {
if (zero) {
general <- "`{name}` must be a single non-negative integer."
} else {
general <- "`{name}` must be a single positive integer."
}
}
check_type(
x, c("double", "integer"), name, general, specific, supplement, ...)
check_length(x, 1, name, general, specific, supplement, ...)
valid <- function(x) is_n(x, zero)
check_content(x, valid, name, general, specific, supplement, ...)
}
#' @rdname check_n
#' @export
is_n <- function(x, zero = FALSE) {
suppressWarnings(
is.numeric(x) &&
is.finite(x) &&
length(x) == 1 &&
as.integer(x) == x &&
if (zero) x >= 0 else x > 0
)
}