R/One-Way-ANOVA-Test.R

Defines functions perform_anova

Documented in perform_anova

#' One-Way ANOVA Test for Differential Gene Expression
#'
#' Performs a one-way ANOVA (Welch correction via \code{\link[stats]{oneway.test}})
#' for every gene (row) in the expression matrix, applies BH correction, and
#' returns a results table together with the list of significant DEGs.
#'
#' @inheritParams perform_t_test
#'
#' @return A named list:
#'   \describe{
#'     \item{Table}{Data.frame with columns \code{G_Symbol}, \code{log2FC},
#'       \code{statistic.F}, \code{p.value}, \code{BH}, \code{fdr}.}
#'     \item{DEGs}{Data.frame of significant gene identifiers.}
#'   }
#'
#' @export
#' @importFrom stats oneway.test p.adjust na.omit quantile
#' @examples
#' library(DGEAR)
#' data("gene_exp_data")
#' result <- perform_anova(dataframe = gene_exp_data,
#'                         con1 = 1, con2 = 10,
#'                         exp1 = 11, exp2 = 20)
#' head(result$Table)
#' result$DEGs
perform_anova <- function(dataframe, con1, con2, exp1, exp2,
                          alpha = 0.05, annot_df = NULL) {
  prep     <- .prepare_data(dataframe, con1, con2, exp1, exp2)
  G_Symbol <- .resolve_symbols(prep$dataframe, annot_df)
  log2FC   <- prep$log2FC
  df_t     <- t(as.matrix(prep$dataframe))   # samples × genes
  
  group <- factor(c(rep("con", con2 - con1 + 1L),
                    rep("tre", exp2 - exp1 + 1L)))
  
  o_results <- t(sapply(seq_len(ncol(df_t)), function(i) {
    res <- oneway.test(df_t[, i] ~ group)
    c(statistic.F = res$statistic, p.value = res$p.value)
  }))
  
  o_stat         <- data.frame(G_Symbol, log2FC, o_results,
                               stringsAsFactors = FALSE)
  o_stat$BH      <- p.adjust(o_stat$p.value, method = "BH")
  o_stat$fdr     <- as.integer(o_stat$BH <= alpha)
  
  DEGs <- data.frame(DEGs = na.omit(o_stat$G_Symbol[o_stat$fdr == 1L]),
                     stringsAsFactors = FALSE)
  list(Table = o_stat, DEGs = DEGs)
}

Try the DGEAR package in your browser

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

DGEAR documentation built on July 3, 2026, 9:07 a.m.