R/enrichGO.R

Defines functions enrichGO

Documented in enrichGO

#' GO term enrichment using Fisher's exact test
#'
#' @param sigGenes either vector of genes of interest or numeric vector containing all genes
#' @param allGenes background of genes
#' @param annotations data base containing all annotations
#' @param ontology which ontology to be used (CC, BP, MF)
#' @param nodeSize minimum node size
#' @param save should result table be saved
#' @param name name
#' @param print should a graphical output be printed
#'
#' @return
#' @export
#'
#' @import topGO
#'
enrichGO <- function(sigGenes, allGenes, annotations = info[["annotations"]], ontology = "CC", nodeSize = 10, save = F, name, print = F) {

  if(hasArg(allGenes)) {

    genes <- rep(0, length(unique(c(sigGenes, allGenes))))
    names(genes) <- unique(c(sigGenes, allGenes))
    genes[sigGenes] <- 1

  }

  else {

    genes <- as.numeric(sigGenes)
    names(genes) <- names(sigGenes)

  }

  GOdata <- new("topGOdata",
                ontology = ontology,
                allGenes = as.factor(genes),
                nodeSize = nodeSize,
                annot = annFUN.gene2GO,
                gene2GO = annotations[names(genes)])


  test.stat <- new("classicCount", testStatistic = GOFisherTest, name = "Fisher test")

  resultFisher <- getSigGroups(GOdata, test.stat)

  allRes <- GenTable(GOdata,
                     classic = resultFisher,
                     orderBy = "classic",
                     topNodes = 20)

  allRes$proteins <- NA
  allRes$genes <- NA
  allRes$names <- NA

  for(i in 1:nrow(allRes)) {
    p <- intersect(sigGenes, getALLProteins(allRes[i, 1], annotationDB = info[["annotations"]]))
    allRes$proteins[i] <- paste(p, collapse = ";")
    allRes$genes[i] <- paste(raw.data[[1]][p, "gene"], collapse = ";")
    allRes$names[i] <- paste(raw.data[[1]][p, "name"], collapse = ";")
  }

  View(allRes)

  if(save) {
    saveThis(allRes, name = name, destination = "dat")
  }


  if(print) {
    setwd(paste0(info[["working directory"]], "/GO"))
    printGraph(GOdata, resultFisher, firstSigNodes = 20, fn.prefix = paste(ontology, if(hasArg(name)) {name}, sep = "_"), useInfo = "all", pdfSW = TRUE, )
    wd()
  }



}
nicohuttmann/htmnanalysis documentation built on Dec. 6, 2020, 3:02 a.m.