Last active
November 17, 2015 20:44
-
-
Save gaballench/da91607fe5f80de5a619 to your computer and use it in GitHub Desktop.
Odds ratio, distance and relative chance in contingency tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Written by Gustavo A. Ballen (gaballench at gmail.com) | |
# https://github.com/gaballench | |
# The input for this function is a contingency table of class 'xtabs' or 'table' with exposure in rows and cases in columns. | |
# Internally it uses the 'pi' notation, or for those using ABCD notation there is an equivalence below: | |
## Model table is as follows | |
# illness | |
# exp NO YES | |
# NO D(1-pi0) C(1-pi1) | |
# YES B(pi0) A(pi1) | |
# The function presents two arguments. 'data' for the object to be analized, and outcome, a string with three posibilities: | |
# 'distance', 'relative' (default), and 'ratio'. | |
# For 'distance' the formula d = pi1 - pi0 is returned | |
# For 'relative' the quotient (i.e., relative risk) r = pi1/pi0 is returned | |
# For 'ratio' the odds ratio is returned | |
# For further details consult Szumilas, M (2010) available below: | |
# http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2938757/ | |
odds <- function(data, outcome = "relative") { | |
margins = apply(data, 1, FUN = sum) | |
#marginsCol = apply(data, 2, FUN = sum) | |
pi0 = data[2, 1]/margins[2] | |
pi1 = data[2, 2]/margins[2] | |
minuspi0 = data[1, 1]/margins[1] # 1 - pi0 | |
minuspi1 = data[1, 2]/margins[1] # 1 - pi1 | |
d = pi1 - pi0 | |
r = pi1/pi0 | |
omega0 = pi0/minuspi0 | |
omega1 = pi1/minuspi1 | |
omega = omega1/omega0 | |
prevalence = marginsCol[2]/sum(marginsCol) | |
sensitivity = pi1/(pi1+minuspi1) | |
specificity = minuspi0/(minuspi1+pi0) | |
pos_pred_val = pi1/(pi1+pi0) | |
neg_pred_val = minuspi0/(minuspi0+minuspi1) | |
if(outcome == "ratio") { | |
return(omega) | |
} | |
if(outcome == "distance"){ | |
return(d) | |
} | |
if(outcome == "relative") { | |
return(r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment