R/dist_to_data_frame.R

#' Helper function for plotting
#' Converts a distance matrix into helpful parameters
#' @param dist_matrix A dist object of pairwise distances between sequences
#' @return A data frame that represents the same information
#' @export
dist_to_data_frame <- function(dist_matrix)
{
  n <- attr(dist_matrix, "Size")
  size_comp <- n*(n-1)/2

  dists <- data.frame(seq1 = rep(NA_integer_, size_comp),
                      seq2 = rep(NA_integer_, size_comp),
                      dist_1_2 = rep(NA_real_, size_comp))

  assign_row <- function(index, dist_matrix, n)
  {
    # find i and j from the index
    jt <- floor(sqrt(2*index)) # could be j-1 or j-2
    j <- jt + 2
    if((jt*(jt-1) < 2*index) && (2*index <= jt*(jt+1)))
    {
      #jt is j-1
      j <- jt + 1
    }
    i <- index - (j-1)*(j-2)/2

    # assign it to the data frame
    new_row <- list(i, j, dist_matrix[index])
    # assignment to the outer dists object
    dists[index, ] <<- new_row
  }

  # assign a row for each index
  purrr::map(1:size_comp, assign_row, dist_matrix, n)
  return(dists)
}
sams25/rcombinator_old documentation built on May 28, 2019, 8:40 a.m.