IsDissimilarity: Check whether an object represents a dissimilarity

View source: R/IsDissimilarity.R

IsDissimilarityR Documentation

Check whether an object represents a dissimilarity

Description

Tests whether an object can reasonably be interpreted as a dissimilarity or distance representation.

Objects inheriting from class "dist" are accepted directly. Numeric square matrices and data frames are checked for finiteness, approximate symmetry, an approximately zero diagonal, and non-negative entries.

Usage

IsDissimilarity(x)

Arguments

x

Object to test. Typically a stats::dist object, numeric matrix, data frame, or another R object.

Details

An object inheriting from class "dist" is returned as TRUE without further matrix validation.

For matrix or data-frame input, x is first converted with as.matrix(). It must then satisfy all of the following requirements:

  • it is numeric;

  • it is two-dimensional;

  • it is square;

  • it contains at least two observations;

  • it contains no missing values;

  • all entries are finite.

More reliable than calling isSymmetric() directly on every possible input. Within floating-point tolerance the check requires a zero diagonal, symmetric and nonnegative entries. The check also reduces accidental classification of a square, symmetric data matrix as a distance matrix.

The floating-point tolerance is calculated as

100 \epsilon \max(1, \max |x|),

For a distance, the triangle inequality must additionally be satisfied, which is not checked here.

Value

Logical scalar.

TRUE if x is recognized as a distance representation; otherwise FALSE.

Note

Small negative values caused by floating-point round-off are tolerated, but the function does not modify the supplied object.

See Also

dist, isSymmetric

Examples

X <- matrix(
  c(
    0, 1, 2,
    1, 0, 3,
    2, 3, 0
  ),
  nrow = 3,
  byrow = TRUE
)

IsDissimilarity(X)
# TRUE

IsDissimilarity(stats::as.dist(X))
# TRUE

IsDissimilarity(matrix(1:6, nrow = 2))
# FALSE

bad <- X
bad[1, 2] <- 10
IsDissimilarity(bad)
# FALSE

FCPS documentation built on Oct. 3, 2026, 9:06 a.m.