R/stats2x2.R

#' produces statistics from a 2 x 2 contingency table
#'
#' \code{stats2x2(matrix)}
#'
#' @param matrix a 2 x 2 matrix or xtabs object
#' @param Ref the index of the reference column, 1 or 2
#'
#' @return a table of calculated statistics and their natural logs

stats2x2 = function(matrix, Ref=1){
  if(class(matrix)[1]=="matrix")matrix=t(matrix)
  if(Ref==2)matrix=rbind(matrix[2,],matrix[1,])
  X = as.numeric(matrix)
  for(i in 1:4) assign(letters[i],X[i])
  n1 = a + b; n2 = c + d;
  p1 = a/n1; SEp1 = sqrt(p1*(1-p1)/n1); p2 = c/n2; SEp2 = sqrt(p2*(1-p2)/n2)
  RD = p1-p2; SE.RD = sqrt((1-p1)*p1/n1+(1-p2)*p2/n2)
  RR = p1/p2; LSE.RR = sqrt(1/a - 1/n1 + 1/b - 1/n2)
  OR = (a*d)/(b*c); LSE.OR = sqrt(1/a + 1/b + 1/c +1/d)
  G1odds = a/b; LSEG1 = sqrt(1/a + 1/b)
  G2odds = c/d; LSEG2 = sqrt(1/c + 1/d)
  M = matrix(,7,4)
  M[1,1] = p1; M[1,2]=log(p1); M[1,3] = SEp1; M[1,4] = log(SEp1)
  M[2,1] = p2; M[2,2]=log(p2); M[2,3] = SEp2; M[2,4] = log(SEp2)
  M[3,1] = G1odds; M[3,2] = log(G1odds); M[3,3] = exp(LSEG1); M[3,4] = LSEG1
  M[4,1] = G2odds; M[4,2] = log(G2odds); M[4,3] = exp(LSEG2); M[4,4] = LSEG2
  M[5,1]= RD; M[5,2]=log(abs(RD));M[5,3] = SE.RD; M[5,4]=log(SE.RD)
  M[6,1]= RR; M[6,2]=log(RR) ;M[6,3] = exp(LSE.RR); M[6,4] = LSE.RR
  M[7,1] = OR; M[7,2] = log(OR); M[7,3] = exp(LSE.OR); M[7,4] = LSE.OR
  M = round(M,3)
  rownames(M) = c("Group1 risk","Group2 risk","Group1 odds","Group2 odds",
                  "Risk Difference", "Relative Risk", "Odds Ratio")
  colnames(M)=c("Estimate","log Est","SE","log SE")
  return(M)
}
helophilus/ColsTools documentation built on May 30, 2019, 4:03 p.m.