Test element-wise near-equality of numeric vectors by allowing for small
numeric errors to make are_equal() safer than ==.
Usage
are_equal(x, y, tol = sqrt(.Machine$double.eps))Arguments
- x, y
Numeric vectors with length larger than zero to compare for equality.
- tol
A small positive number. Numbers that differ less than
tolare considered equal.
Value
A vector with logical values (TRUE, FALSE or NA) indicating if
elements in x and y are equal to each other. NA is returned for
comparisons involving numeric NA (i.e., NA_integer_ or NA_real_),
NaN, or infinite values with the same sign.
Details
are_equal() allows for small numeric errors when comparing numbers. Such
numeric errors can arise because of rounding or representation error. As the
Note at == warns, x == round(x) does not allow for such errors
but tests exact equality.
Acknowledgement
Code abs(x - y) < tol was taken from
dplyr::near().
See also
checkinput::is_natural() to check for element-wise near-equality to natural
numbers; all.equal() to check more generally for near-equality;
identical(), not_in() and match() (containing %in% and, from R
4.6.0 onwards, '%notin%') to check for exact (in)equality, with
Comparison to do so using binary operators;
R FAQ 7.31
for background on numerical equality;
the vignette Type coercion in package checkinput:
vignette("Type_Coercion", package = "checkinput").
Other functions to check equality:
check_case(),
get_file_path(),
not_in(),
replace_vals()
Examples
x <- sqrt(2)^2
x == 2 # FALSE
#> [1] FALSE
x - 2 # about 4.44e-16
#> [1] 4.440892e-16
are_equal(x = x, y = 2) # TRUE
#> [1] TRUE
are_equal(x = c(2, 3, 3, NA, Inf),
y = c(2, 3, 3 + 1e-8, NA, Inf))
#> [1] TRUE TRUE TRUE NA NA
are_equal(x = 3, y = c(2, 3, 3 + 1e-8, NA, Inf))
#> [1] FALSE TRUE TRUE NA FALSE