R/dist.R

Defines functions distSparse

Documented in distSparse

# sparse distance metrics. Sparsity is strange for distance metricis, because low values (close to zero) are the most interesting ones, so distance metrics are normally not sparse.

distSparse <- function(M, method = "euclidean", diag = FALSE) {
  
  if (!is(M, "dMatrix")) {
    M <- Matrix(M, sparse = T)
  }
  
  P <- crossprod(M)
  
  # only do elements that have shared non-zeros, i.e. P is non-zero
  N <- as(P, "nMatrix") * 1
  S <- Diagonal(x = colSums(M^2)) %*% N
  
  # euclidean distance
  D <- S + t(S) - 2 * P
  D <- as(D, "symmetricMatrix")
  D@x <- sqrt(D@x)
  
  # reverse to similarity
  D <- max(D)-D	

  if (!diag) {
    diag(D) <- 0
  }
  
  return(drop0(D))
  
}

Try the qlcMatrix package in your browser

Any scripts or data that you put into this service are public.

qlcMatrix documentation built on May 2, 2019, 9:14 a.m.