R/getNormFactors.R

Defines functions getNormFactors

Documented in getNormFactors

#' Get normalization factors from peak data.frame
#'
#' @param peaksdf       data.frame with peaks information as generated by peaks2df()
#' @param targetMz      Numeric, target mass
#' @param tol           Numeric, tolerance around targetMz
#' @param tolppm        Logical, is the tolerance provided in ppm (TRUE) or Daltion (FALSE)
#' @param allowNoMatch  Logical, stop if targetMz is not fround in single spectrum?
#'                      If TRUE spectra without targetMz match will be excluded.
#'
#' @return              List with two entries:
#'                                       norm_factor The normalization factor for each spectrum
#'                                       specIdx     The index of the spectra with a match for targetMz
#'
#' @importFrom dplyr pull %>% filter arrange
#' @export
#' 
#' @examples
#' data(Blank2022peaks)
#' getNormFactors(peaks2df(Blank2022peaks), targetMz = 760.585, tol = 0.1, tolppm = FALSE)
getNormFactors <- function(peaksdf, targetMz, tol, tolppm = TRUE, allowNoMatch = TRUE) {
  plot_Idx <- sort(unique(peaksdf$plotIdx))

  if (tolppm) {
    tol <- (tol / 1e6)
    resdf <- peaksdf %>%
      mutate(match = .data$mz > targetMz - .data$mz * tol & .data$mz < targetMz + .data$mz * tol)
  } else {
    resdf <- peaksdf %>%
      mutate(match = .data$mz > targetMz - tol & .data$mz < targetMz + tol)
  }

  f_resdf <- resdf %>%
    filter(match) %>%
    mutate(mz.diff = round(targetMz - .data$mz, 4)) %>%
    group_by(.data$plotIdx) %>%
    filter(abs(.data$mz.diff) == min(abs(.data$mz.diff))) %>%
    arrange(.data$plotIdx)


  if (!all(plot_Idx %in% (f_resdf %>% pull(.data$plotIdx)))) {
    if (!allowNoMatch) {
      stop("Could not find ", targetMz, " for all spectra! Consider adjusting tol.\n")
    }
    warning("Could not find ", targetMz, " in spectrum ", paste(which(!(plot_Idx %in% (f_resdf %>% pull(.data$plotIdx)))), collapse = ", "), ".\n")
    specIdx <- which(plot_Idx %in% (f_resdf %>% pull(.data$plotIdx)))
  } else {
    specIdx <- plot_Idx
  }
  if (length(specIdx) < 1) {
    stop("Could not find targetMz in any spectrum! Consider adjusting tol.\n")
  }
  return(list(
    norm_factor = pull(f_resdf, .data$int),
    specIdx = specIdx
  ))
}

Try the MALDIcellassay package in your browser

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

MALDIcellassay documentation built on Sept. 11, 2024, 8:29 p.m.