File: binomial_test.R

package info (click to toggle)
r-bioc-mutationalpatterns 3.16.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,360 kB
  • sloc: sh: 8; makefile: 2
file content (44 lines) | stat: -rw-r--r-- 1,182 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#' Binomial test for enrichment or depletion testing
#'
#' This function performs lower-tail binomial test for depletion and
#' upper-tail test for enrichment
#'
#' @param p Probability of success
#' @param n Number of trials
#' @param x Observed number of successes
#' @param p_cutoffs Significance cutoff for the p value. Default: 0.05
#' @return A data.frame with direction of effect (enrichment/depletion),
#' P-value and significance asterisks
#'
#' @examples
#' binomial_test(0.5, 1200, 543)
#' binomial_test(0.2, 800, 150)
#' @export

binomial_test <- function(p, n, x, p_cutoffs = 0.05) {
  # Calculate expected number of successes
  expected <- p * n

  # Handle depletion
  if (x < expected) {
    # do lower tail test
    pval <- stats::pbinom(x, n, p, lower.tail = TRUE)
    effect <- "depletion"
  }

  # Handle enrichment
  else {
    # do upper tail test
    pval <- stats::pbinom(x - 1, n, p, lower.tail = FALSE)
    effect <- "enrichment"
  }

  # make test two sided.
  pval <- 2 * min(pval, 1 - pval)

  # Add significance asteriks
  significant <- .get_sig_star(pval, p_cutoffs)

  res <- data.frame("effect" = factor(effect), pval, significant)
  return(res)
}