all_equal_numeric2: Compare if two objects are nearly equal

View source: R/miscellaneous_functions.R

all_equal_numeric2R Documentation

Compare if two objects are nearly equal

Description

Compare if two objects are nearly equal

Usage

all_equal_numeric2(
  target,
  current,
  tolerance = sqrt(.Machine[["double.eps"]]),
  scaled = FALSE,
  ...
)

Arguments

target

R object.

current

other R object, to be compared with target.

tolerance

numeric \ge 0. Differences smaller than tolerance are not reported. The default value is close to 1.5e-8.

scaled

A logical value. See Details.

...

further arguments for different methods, notably the following two, for numerical comparison:

Details

Non-numeric objects are passed to all.equal. Relative differences are typically reported if scaled = TRUE which is equivalent to argument scale = NULL of all.equal. In fact, in this case, all.equal is called with countEQ = FALSE. However, the mean across absolute differences of those (numeric) elements that differ by at least tolerance is reported if scaled = FALSE. This behavior differs from all.equal in R v3.6.2 with countEQ = FALSE and scale = 1 which reports the mean absolute difference of those elements that differ at all. See examples.

See Also

all.equal

Examples

N <- 50
diff <- 0.1
tiny_diff <- 1e-14 # < sqrt(.Machine[["double.eps"]])
tol <- sqrt(.Machine[["double.eps"]]) # default value of `all.equal`

x <- runif(n = N)

# Set up y1 as identical to x except for one element
y1 <- x
y1[[2L]] <- y1[[2L]] + diff

# Set up y2 as almost identical to y1
y2 <- y1
y2[5:10] <- y2[5:10] + tiny_diff

## ==> expect that comparisons of `y1` against `x` and `y2` against `x`
## result in the same mean absolute difference because `y1` and `y2`
## differ by less than `tolerance`
all.equal(y1, x, tolerance = tol, scale = 1, countEQ = FALSE)
all.equal(y2, x, tolerance = tol, scale = 1, countEQ = FALSE)

all_equal_numeric2(y1, x, tolerance = tol, scaled = FALSE)
all_equal_numeric2(y2, x, tolerance = tol, scaled = FALSE)

all_equal_numeric2(list(y2, y1), list(x, x), tolerance = tol, scaled = FALSE)


## Example with non-numeric elements
data("iris", package = "datasets")
iris[, "Species"] <- as.character(iris[, "Species"])
iris2 <- iris # Column "Species" is a character vector
iris2[1, "Sepal.Length"] <- 0.1 + iris2[1, "Sepal.Length"]
iris2[2:7, "Sepal.Length"] <- iris2[2:7, "Sepal.Length"] + tiny_diff
iris2[10, "Species"] <- "Test"

all.equal(iris, iris2, tolerance = tol, scale = 1, countEQ = FALSE)
all_equal_numeric2(iris, iris2, tolerance = tol, scaled = FALSE)

DrylandEcology/rSW2utils documentation built on Dec. 9, 2023, 10:44 p.m.