Confidence interval(CI) for the OR(odds ratio) and RR(relative risk)

Cinni Patel
2 min readFeb 12, 2021

Calculate and output for the confidence interval for the Odds Ratioand Relative Risk.

Ref http://www.rdocumentation.org/packages/base/versions/3.6.2/topics/log

For simplicity, I have assigned exposure and outcome groups to a,b,c and d variables inside the function.

with(acupuncture.data,table(group,migraine)) -> con.tab

a <- con.tab[1,2]
b <- con.tab[1,1]
c <- con.tab[2,2]
d <- con.tab[2,1]

Steps to calculate Confidence Interval for Odds Ratio

  • Calculate Odds Ratio (a*d)/(b*c)
  • Calculate Point Estimate (Log of Odds Ratio so that the value looks normal)
  • Find Margin Error for 95% confidence interval 1.96 * sqrt((1/a) + (1/b) + (1/c)+ (1/d))
  • Apply +- and Exponentiate value
  • Round CI’s Upper and lower boundary

Steps to calculate Confidence Interval for Relative Risk

  • Calculate Odds Ratio (a/(a+b)) / (c/(c+d))
  • Calculate Point Estimate (Log of Relative Risk so that the value looks normal)
  • Find Margin Error for 95% confidence interval 1.96*(sqrt( (b/(a*(a+b))) + (d/(c*(c+d)))))
  • Apply +- and Exponentiate value
  • Round CI’s Upper and lower boundary

Function to calculate CI for OR and RR

or.calc <- function(expose,outcome){

con.tab <- table(expose,outcome)

or.chi <- chisq.test(con.tab)$p.value

a <- con.tab[1,2]
b <- con.tab[1,1]
c <- con.tab[2,2]
d <- con.tab[2,1]

#------------------------ Odds Ratio (OR) ---------------------------------#
odds.ratio <- (a*d)/(b*c)
or.point.estimate <- log(odds.ratio)
or.margin.of.error <- 1.96 * sqrt((1/a) + (1/b) + (1/c)+ (1/d))
or.ci.lower_bound <- round(exp(or.point.estimate - or.margin.of.error), digits=2)
or.ci.upper_bound <- round(exp(or.point.estimate + or.margin.of.error), digits=2)

#------------------------ Relative Risk (RR) ------------------------------#
relative.risk <- (a/(a+b)) / (c/(c+d))
rr.point.estimate <- log(relative.risk)
rr.margin.of.error <- 1.96*(sqrt( (b/(a*(a+b))) + (d/(c*(c+d)))))
rr.ci.upper_bound <- round(exp(rr.point.estimate - rr.margin.of.error), digits=2)
rr.ci.lower_bound <- round(exp(rr.point.estimate + rr.margin.of.error), digits=2)

return(list(con.tab,
p_value=or.chi,
OR=odds.ratio,OR_CI_lower_bound= or.ci.lower_bound, OR_CI_upper_bound= or.ci.upper_bound,
RR=relative.risk,RR_CI_upper_bound= rr.ci.upper_bound, RR_CI_lower_bound=rr.ci.lower_bound))
}

Call the function

with(acupuncture.data,or.calc(group,migraine))## [[1]]
## outcome
## expose 0 1
## 0 13 183
## 1 11 194
##
## $p_value
## [1] 0.7459374
##
## $OR
## [1] 0.7981761
##
## $OR_CI_lower_bound
## [1] 0.35
##
## $OR_CI_upper_bound
## [1] 1.83
##
## $RR
## [1] 0.9866137
##
## $RR_CI_upper_bound
## [1] 0.94
##
## $RR_CI_lower_bound
## [1] 1.04

--

--

Cinni Patel

Data Scientist — Generalist | Big data Enthusiast | Student at St Thomas Uni