Skip to content

add contingency function #9

@zx8754

Description

@zx8754
#' Calculate Relative Risk, etc.
#'
#' Calculate Relative Risk, etc. based on table output
#' @param x Output of \code{table()}, defaults to \code{NA}.
#' @param desc description column, string, defaults to \code{NA}.
#' @author Tokhir Dadaev
#' @examples
#' set.seed(1); myTable <- table(
#' data.frame(CaCo = sample(c(0,1), 1000, replace = TRUE),
#'            Mutation = sample(c(rep(0, 20),1), 1000, replace = TRUE)))
#' contingency(myTable, "sss")
#' 
contingency <- function(x, desc = NA){
  #x = myTable
  sums <- addmargins(x)
  propsRows <- prop.table(x, margin = 1)
  propsCols <- prop.table(x, margin = 2)

  
  #Absolute risk in controls
  AR0 <- sums[2, 1] / sums[3, 1]
  #Absolute risk in cases
  AR1 <- sums[2, 2] / sums[3, 2]
  #Absolute risk reduction (ARR)
  ARR <- AR0 - AR1
  #Relative risk (RR)
  RR <- AR1 / AR0
  #Relative risk reduction
  RRR <- 1 - RR
  #Odds in treatment group
  ORTreatment <- sums[2, 2]/sums[1, 2]
  #Odds in control group
  ORControl <- sums[2, 1]/sums[1, 1]
  #Odds ratio (OR)
  OR <- ORTreatment/ORControl
  #Number needed to treat (NNT)
  NNT <- 1/ARR
  
  #Fisher Stats
  # chisq.test(d)
  f <- fisher.test(x)
  
  res <- data.frame(AR0, AR1,ARR,
             RR, RRR,
             ORTreatment, ORControl, OR,
             NNT,
             fisher.OR = f$estimate,
             fisher.Lo.CI = f$conf.int[1],
             fisher.Up.CI = f$conf.int[2],
             fisher.P = f$p.value)
  if(!is.na(desc)) { res <- cbind(Description = desc, res)}
  
  #return
  res
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions