Calculates distances between the matrix rows, or between the rows of two matrices.
tgs_dist(
x,
y = NULL,
diag = FALSE,
upper = FALSE,
tidy = FALSE,
threshold = Inf
)If 'tidy' is 'FALSE' - the output is similar to that of 'dist' function, or if 'y' is given, a matrix of the distances between the rows of 'x' (its rows) and the rows of 'y' (its columns). If 'tidy' is 'TRUE' - 'tgs_dist' returns a data frame, where each row represents distances between two pairs of original rows.
This function is very similar to 'package:stats::dist'. Unlike the latter it uses all available CPU cores to compute the distances in a much faster way.
Unlike 'package:stats::dist' 'tgs_dist' uses always "euclidean" metrics (see 'method' parameter of 'dist' function). Thus:
'tgs_dist(x)' is equivalent to 'dist(x, method = "euclidean")'
If 'y' is given, 'tgs_dist' returns the distances between each row of 'x'
and each row of 'y': 'tgs_dist(x, y)' is equivalent to
as.matrix(dist(rbind(x, y)))[1:nrow(x), nrow(x) + 1:nrow(y)], and
missing values are treated as in 'dist'. 'diag' and 'upper' are then ignored.
'tgs_dist' can output its result in "tidy" format: a data frame with three columns named 'row1', 'row2' and 'dist'. Only the distances that are less or equal than the 'threshold' are reported. Distance between row number X and Y is reported only if X < Y, unless 'y' is given ('row1' is then a row of 'x' and 'row2' a row of 'y'). 'diag' and 'upper' parameters are ignored when the result is returned in "tidy" format.
With BLAS ('tgs_use.blas') the squared distance between points x and y is computed as 'sum(x^2) + sum(y^2) - 2 * sum(x * y)', which loses precision for points that are close relative to their norms. A squared distance that is within the rounding error of this formula is computed directly, so identical points are at distance 0.
# \donttest{
# Note: all the available CPU cores might be used
set.seed(seed = 0)
rows <- 100
cols <- 1000
vals <- sample(1:(rows * cols / 2), rows * cols, replace = TRUE)
m <- matrix(vals, nrow = rows, ncol = cols)
m[sample(1:(rows * cols), rows * cols / 1000)] <- NA
r <- tgs_dist(m)
r2 <- tgs_dist(m, m[1:10, ])
# }