Nothing
#' Convert a similarity or distance matrix to a 'dist' object
#'
#' This function converts a similarity matrix (with values between 0 and 1 and 1s on the diagonal)
#' or a distance matrix into a 'dist' object. The user can specify the method used to transform
#' similarity values into distances.
#'
#' @param dist_mat A square matrix (similarity or distance) or a 'dist' object.
#' @param similarity_transform Method to convert similarity to distance. Either \code{"linear"} (default) or \code{"sqrt"}.
#' \itemize{
#' \item{\code{"linear"}: Applies a linear transformation to convert similarity to distance.}
#' \item{\code{"sqrt"}: Applies the square root transformation to convert similarity to distance.}
#' }
#' @return An object of class 'dist'.
#' @keywords internal
convert_to_dist <- function(dist_mat, similarity_transform = c("linear", "sqrt")) {
# Match and validate the transformation method
similarity_transform <- match.arg(similarity_transform)
# If already a 'dist' object, return it directly
if (inherits(dist_mat, "dist")) {
return(dist_mat)
}
# Ensure input is a matrix
if (!is.matrix(dist_mat)) {
stop("Input must be a matrix or a 'dist' object.")
}
# Check if the matrix is square
if (nrow(dist_mat) != ncol(dist_mat)) {
stop("Matrix must be square.")
}
# Check for symmetry
is_symmetric <- all(dist_mat == t(dist_mat))
# Check if it looks like a similarity matrix
is_sim_matrix <- all(dist_mat >= 0 & dist_mat <= 1) && all(diag(dist_mat) == 1)
if (is_sim_matrix && is_symmetric) {
# Apply the selected transformation method
if (similarity_transform == "sqrt") {
dist_converted <- sqrt(1 - dist_mat)
} else if (similarity_transform == "linear") {
dist_converted <- 1 - dist_mat
}
return(as.dist(dist_converted))
} else {
# If not a similarity matrix, assume it's a distance matrix
return(as.dist(dist_mat))
}
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.