R/allele_binary.R

Defines functions allele_to_binary

Documented in allele_to_binary

# Declare global variables once
utils::globalVariables(c("Marker"))

#' Convert allele sizes to binary
#'
#' This function converts microsatellite allele sizes into binary matrices.
#'
#' @param data Input data frame with Marker, Genotype, and allele sizes
#' @param repeat_lengths Repeat length info
#' @return A list of binary matrices
#' @export
allele_to_binary <- function(data, repeat_lengths) {
  results <- list()
  structure_results <- list()

  for (marker in unique(data$Marker)) {
    marker_data <- subset(data, Marker == marker)
    alleles <- unlist(marker_data[, -(1:2)])
    alleles <- alleles[alleles != 0]
    sorted_alleles <- sort(unique(alleles))

    # Binary matrix
    binary_matrix <- matrix(0, nrow = nrow(marker_data), ncol = length(sorted_alleles))
    rownames(binary_matrix) <- marker_data$Genotype
    colnames(binary_matrix) <- sorted_alleles

    # Structure positions
    structure_matrix <- matrix(-9, nrow = nrow(marker_data), ncol = ncol(marker_data) - 2)
    rownames(structure_matrix) <- marker_data$Genotype
    colnames(structure_matrix) <- paste0("Pos_", seq_len(ncol(structure_matrix)))

    for (i in seq_len(nrow(marker_data))) {
      genotype_alleles <- unlist(marker_data[i, -(1:2)])
      for (j in seq_along(genotype_alleles)) {
        allele <- genotype_alleles[j]
        if (allele != 0 && allele %in% sorted_alleles) {
          # Binary
          binary_matrix[i, which(sorted_alleles == allele)] <- 1
          # Position index
          structure_matrix[i, j] <- match(allele, sorted_alleles)
        }
      }
    }

    results[[marker]] <- binary_matrix
    structure_results[[marker]] <- structure_matrix
  }

  list(binary = results, structure = structure_results)
}

Try the ALSBinary package in your browser

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

ALSBinary documentation built on Aug. 9, 2026, 5:06 p.m.