R/count_ion_annotations.R

Defines functions count_ion_annotations

Documented in count_ion_annotations

#' Generates a Summary Table of the Number of Ions per Residue
#'
#' @description A simple summary table of the number of ions per residues
#'
#' @param MatchedPeaks A matched_peaks object generated by get_matched peaks. Required.
#' @param IncludeIsotopes A logical to indicate whether isotopes should be included. Default is FALSE.
#'
#' @examples
#' \dontrun{
#'
#' # Test bottom up data
#' BU_Peak <- get_peak_data(ScanMetadata = BU_ScanMetadata, ScanNumber = 31728)
#' BU_Match <- get_matched_peaks(ScanMetadata = BU_ScanMetadata, PeakData = BU_Peak)
#'
#' count_ion_annotations(MatchedPeaks = BU_Match)
#'
#' }
#'
#' @export
count_ion_annotations <- function(MatchedPeaks,
                                  IncludeIsotopes = FALSE) {

  ##################
  ## CHECK INPUTS ##
  ##################

  # Assert that Matched Peaks is an object of the matched_peaks
  if ("matched_peaks" %in% class(MatchedPeaks) == FALSE) {
    stop("MatchedPeaks is not an object of the matched_peaks class generated by get_matched_peaks.")
  }

  # Assert that Include Isotopes is a single logical
  if (is.na(IncludeIsotopes) || is.logical(IncludeIsotopes) == FALSE || length(IncludeIsotopes) > 1) {
    stop("IncludeIsotopes needs to be a single logical: a TRUE or FALSE.")
  }

  ####################
  ## GENERATE TABLE ##
  ####################

  # Split the sequence and number results
  SplitSeq <- attr(MatchedPeaks, "pspecter")$Sequence %>% strsplit("") %>% unlist()
  Residues <- paste0(SplitSeq, 1:length(SplitSeq))

  # Pull Fragment Table and add Peptide N Position
  FragmentTable <- MatchedPeaks

  # Remove isotopes if indicated
  if (IncludeIsotopes == FALSE) {
    FragmentTable <- FragmentTable[FragmentTable$Isotope == "M",]
  }

  # Pull Ions
  `Ion Names` <- lapply(Residues, function(Res) {
    ResSub <- FragmentTable[FragmentTable$Residue == Res,]
    if (nrow(ResSub) > 0) {
      return(paste0(ResSub$Ion, "(+", ResSub$Z, ")", ResSub$Isotope))
    }
  })

  # Get Counts
  `Number of Ions` <- `Ion Names` %>% lapply(length) %>% unlist()

  # Collapse Ion Names
  `Ion Names` <- `Ion Names` %>% lapply(function(x) paste(x, collapse = " & ")) %>% unlist()

  # Return data table
  return(
    data.table::data.table("Order" = 1:length(SplitSeq), Residues,
                           "Number of Ions" = `Number of Ions`, "Ion Names" = `Ion Names`)
  )

}
EMSL-Computing/pspecterlib documentation built on Jan. 28, 2024, 8:13 p.m.