R/addAccessibilityShift.R

Defines functions addAccessibilityShift

Documented in addAccessibilityShift

#' @title \code{addAccessibilityShift}
#'
#' @description \code{addAccessibilityShift} will add a new condition to the SummarizedExperiment output of extractRegion,
#' 								which will contain the difference in accessibility between two conditions
#'
#' @param CountSE The SummarizedExperiment object output from extractRegion
#' @param foreground Group that will be used as the foreground for the subtraction of accessibility
#' @param background Group that will be used as the background for the subtraction of accessibility
#' @param assayName The name given to the new assay that is difference in accessibility between foreground and background.
#'
#' @return countSE a SummarizedExperiment containing coverage for the given input cell populations.
#'
#' @examples
#' \dontrun{
#' # CountSE is a SummarizedExperiment generated by extractRegion()
#' countSE <- MOCHA::addAccessibilityShift(
#'   CountSE = CountSE,
#'   foreground = "Condition1",
#'   background = "Condition2",
#'   assayName = "AccessibilityChanges"
#' )
#' }
#' @export
#'

addAccessibilityShift <- function(CountSE,
                                  foreground,
                                  background,
                                  assayName = NULL) {
  groupNames <- names(SummarizedExperiment::assays(CountSE))


  if (is.null(assayName)) {
    assayName <- paste("Delta:", foreground, "-", background, sep = "")
  }

  metaFile <- SummarizedExperiment::colData(CountSE)
  outDir <- CountSE@metadata$Directory

  if (is.na(outDir)) {
    stop("Missing coverage file directory.")
  }

  if (!all(c(foreground, background) %in% groupNames)) {
    stop("Foreground & Background are not found. Try running names(SummarizedExperiment::assays(CountSE)) to verify all options")
  } else if (assayName %in% groupNames) {
    stop("The name of this differential is already present in the CountSE object. Try setting a different name via assayName")
  } else {
    fore <- SummarizedExperiment::assays(CountSE)[[foreground]]
    back <- SummarizedExperiment::assays(CountSE)[[background]]

    if (all(fore$chr == back$chr & fore$Locus == back$Locus)) {
      delta <- list(data.frame(
        chr = fore$chr, Locus = fore$Locus,
        Counts = fore$Counts - back$Counts,
        Groups = rep(assayName, length(fore$Counts))
      ))
      names(delta) <- assayName

      SummarizedExperiment::assays(CountSE) <- append(SummarizedExperiment::assays(CountSE), delta)

      return(CountSE)
    } else {
      stop("CountSE data frame is inconsistent. The foreground and background chr/locus don't align.")
    }
  }
}

Try the MOCHA package in your browser

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

MOCHA documentation built on May 29, 2024, 2:25 a.m.