Check that x is a vector of the correct length with numbers of the correct
sign.
Usage
is_number(x, allow_zerolength = FALSE, allow_NA = FALSE, allow_NaN = FALSE)
all_numbers(x, allow_zerolength = FALSE, allow_NA = FALSE, allow_NaN = FALSE)
is_nonnegative(
x,
allow_zerolength = FALSE,
allow_NA = FALSE,
allow_NaN = FALSE
)
all_nonnegative(
x,
allow_zerolength = FALSE,
allow_NA = FALSE,
allow_NaN = FALSE
)
is_positive(x, allow_zerolength = FALSE, allow_NA = FALSE, allow_NaN = FALSE)Arguments
- x
object to check.
- allow_zerolength
TRUEorFALSE: allow zero-lengthxof the correct type?- allow_NA
TRUEorFALSE: allow NA of the correct type inx?- allow_NaN
TRUEorFALSE: allowNaN?
Value
TRUE or FALSE indicating if x is a vector of the correct length only
containing allowed numbers.
Details
is_number(), all_numbers(), all_nonnegative() and is_nonnegative()
return TRUE for zero, whereas is_positive() returns FALSE for zero.
is_number(), is_nonnegative(), and is_positive() return TRUE for x
with length one. all_numbers() and all_nonnegative() return TRUE for
x with length larger than zero.
All these functions return TRUE:
for numeric-type zero-length
xifallow_zerolengthisTRUE.for
-InfandInfif it has the correct signfor
NA_integer_andNA_real_ifallow_NAisTRUE(even then they returnFALSEforNA_complex_because that has modecomplexinstead ofnumeric)for
NaN(which has modenumeric, despite meaning 'not a number') ifallow_NaNisTRUE.
Programming notes
is.numeric() checks the mode() of x, which is numeric for
floating-point numbers such as 3.2 and integers such as 3L. In contrast,
class(x) == "numeric" (or, more robust, inherits(x = x, what = "numeric"))
would check the class() of x which is numeric for floating-point numbers
but integer for integers (see the Note on names in is.numeric()).
See also
Other collections of checks on type and length:
all_characters(),
all_names(),
is_logical(),
is_natural(),
is_path(),
is_zerolength()
Examples
is_number(x = 1) # TRUE
#> [1] TRUE
is_number(x = 3.14) # TRUE
#> [1] TRUE
is_number(x = c(1, 2)) # FALSE: incorrect length
#> [1] FALSE
all_numbers(x = c(1, 2)) # TRUE
#> [1] TRUE
is_number(x = "a") # FALSE: incorrect type
#> [1] FALSE
is_number(x = numeric(0)) # FALSE: incorrect length
#> [1] FALSE
is_number(x = numeric(0), allow_zerolength = TRUE) # TRUE
#> [1] TRUE
is_number(x = NA_real_) # FALSE
#> [1] FALSE
is_number(x = NA_real_, allow_NA = TRUE) # TRUE
#> [1] TRUE
is_number(x = NA_character_, allow_NA = TRUE) # FALSE: incorrect type
#> [1] FALSE
is_number(x = NaN, allow_NA = TRUE) # FALSE, need allow_NaN = TRUE to allow NaN
#> [1] FALSE
is_number(x = NaN, allow_NaN = TRUE) # TRUE
#> [1] TRUE
is_number(x = Inf) # TRUE
#> [1] TRUE
is_nonnegative(x = 3) # TRUE
#> [1] TRUE
is_nonnegative(x = 0) # TRUE
#> [1] TRUE
all_nonnegative(x = c(3, 0)) # TRUE
#> [1] TRUE
all_nonnegative(x = numeric(0), allow_zerolength = TRUE) # TRUE
#> [1] TRUE
is_positive(x = 3) # TRUE
#> [1] TRUE
is_positive(x = 0) # FALSE
#> [1] FALSE