R/chem_FUN.R

Defines functions ppm_to_mda mda_to_ppm get_mass_range mzs_to_mass

Documented in get_mass_range mzs_to_mass

#' @title convert charged m/z to neutral mass
#'
#' @description 
#'  convert charged m/z to neutral mass with a list of predefined adducts
#'      reject those with a mass under or equal to 0
#'
#' @param mzs vector of floats, represent m/z
#' @param adducts vector of strings, represent name of the adduct
#'
#' @return matrix with columns
#'  \enumerate{
#'      \item adduct
#'      \item ion_mz
#'      \item mass
#' }
#'
#' @examples
#' \dontrun{mzs_to_mass(443.1247895, c("M+H", "M+2H"))}
mzs_to_mass <- function(mzs, adducts) {
    utils::data(adducts_df, package = "MetaboSeeker")
    adducts <- adducts_df[which(adducts_df[, 1] %in% adducts), ]
    result <- do.call(rbind, lapply(mzs, function(mz) 
        matrix(c(rep(mz, nrow(adducts)), adducts[, 1], 
            mz * adducts$Charge / adducts$Mult + adducts$Mass), 
            ncol = 3, dimnames = list(c(), c("mz", "adduct", "mass")))))
    result[which(as.numeric(result[, "mass"]) > 0), , drop = FALSE]
}

#' @title Get mass error range
#' 
#' @description.
#' Compute mass error range with a tolerance in ppm and / or in mda
#'
#' @param mass vector of floats representing masses
#' @param ppm float, optional, 0 by default
#' @param mda float, optional, 0 by default
#'
#' @return matrix with two column: one row for each mass provided in the masses param, columns represent borns min & max
#'
#' @examples
#' \dontrun{get_mass_range(c(443.1247985, 190.053578), ppm = 2)}
#' \dontrun{get_mass_range(c(443.1247985, 190.053578), mda = 1)}
get_mass_range <- function(mass, ppm = 0, mda = 0) {
    mass_range <- if (ppm > 0) matrix(c(mass - (mass * ppm * 10**-6), 
            mass + (mass * ppm * 10**-6)), ncol = 2)
        else matrix(rep(mass, 2), ncol = 2)
    mass_range[, 1] <- mass_range[, 1] - (mda * 10**-3)
    mass_range[, 2] <- mass_range[, 2] + (mda * 10**-3)
    mass_range
}

# just a remember
mda_to_ppm <- function(mass, mda) mda * 10**3 * mass
ppm_to_mda <- function(mass, ppm) ppm * 10**-3 / mass
    
shutinet/MetaboSeeker documentation built on Sept. 9, 2020, 12:41 a.m.