| name | epidemiology-methods |
| description | Epidemiological analysis methods in R for cohort, case-control, confounding control, and causal inference. |
Epidemiology Methods in R
Overview
Comprehensive epidemiological analysis methods covering study designs, measures of association, confounding control, propensity scores, and causal inference using R.
Measures of Association
Risk and Rate Measures
library(epiR)
table_data <- matrix(c(a, b, c, d), nrow = 2, byrow = TRUE)
colnames(table_data) <- c("Disease+", "Disease-")
rownames(table_data) <- c("Exposed", "Unexposed")
epi.2by2(as.table(table_data), method = "cohort.count")
epi.2by2(as.table(table_data), method = "case.control")
epi.2by2(as.table(table_data), method = "cross.sectional")
Incidence Rates
library(Epi)
lex <- Lexis(
entry = list(age = entry_age, cal = entry_date),
exit = list(cal = exit_date),
exit.status = event,
data = cohort_data
)
lex_split <- splitLexis(lex, breaks = seq(30, 80, by = 10), time.scale = "age")
rates <- tapply(status(lex_split, "exit"),
timeBand(lex_split, "age", type = "factor"),
function(x) sum(x == 1))
pyrs <- tapply(dur(lex_split),
timeBand(lex_split, "age", type = "factor"),
sum)
rates / pyrs * 1000
Standardized Rates
library(epitools)
ageadjust.direct(
count = cases,
pop = population,
stdpop = standard_population
)
ageadjust.indirect(
count = observed_cases,
pop = study_population,
stdcount = expected_rates * std_population,
stdpop = standard_population
)
Regression Models
Logistic Regression (Case-Control, Cross-Sectional)
fit <- glm(outcome ~ exposure + covariate1 + covariate2,
family = binomial(link = "logit"),
data = df)
exp(cbind(OR = coef(fit), confint(fit)))
library(broom)
tidy(fit, exponentiate = TRUE, conf.int = TRUE)
Conditional Logistic Regression (Matched Case-Control)
library(survival)
fit <- clogit(
case ~ exposure + covariate + strata(matched_set),
data = matched_data
)
summary(fit)
exp(coef(fit))
Poisson Regression (Rates)
fit <- glm(
events ~ exposure + age_group + offset(log(person_years)),
family = poisson(link = "log"),
data = df
)
exp(cbind(RR = coef(fit), confint(fit)))
library(AER)
dispersiontest(fit)
library(MASS)
fit_nb <- glm.nb(
events ~ exposure + age_group + offset(log(person_years)),
data = df
)
Log-Binomial Regression (Risk Ratios)
fit <- glm(
outcome ~ exposure + covariates,
family = binomial(link = "log"),
data = df
)
library(sandwich)
library(lmtest)
fit_pois <- glm(
outcome ~ exposure + covariates,
family = poisson(link = "log"),
data = df
)
coeftest(fit_pois, vcov = sandwich)
Confounding Control
Stratified Analysis
library(epiR)
mh_result <- epi.2by2(
stratified_table,
method = "cohort.count"
)
mh_result$massoc$RR.mh
mh_result$massoc$chisq.mh
Regression Adjustment
fit_adjusted <- glm(
outcome ~ exposure + confounder1 + confounder2 + confounder3,
family = binomial(),
data = df
)
fit_crude <- glm(outcome ~ exposure, family = binomial(), data = df)
(exp(coef(fit_crude)["exposure"]) - exp(coef(fit_adjusted)["exposure"])) /
exp(coef(fit_crude)["exposure"]) * 100
Propensity Score Methods
Propensity Score Estimation
library(MatchIt)
ps_model <- glm(
treatment ~ age + sex + bmi + smoking + comorbidities,
family = binomial(),
data = df
)
df$ps <- predict(ps_model, type = "response")
library(ggplot2)
ggplot(df, aes(x = ps, fill = factor(treatment))) +
geom_density(alpha = 0.5) +
labs(title = "Propensity Score Distribution by Treatment")
Propensity Score Matching
library(MatchIt)
match_out <- matchit(
treatment ~ age + sex + bmi + smoking + comorbidities,
data = df,
method = "nearest",
distance = "glm",
caliper = 0.2,
ratio = 1
)
summary(match_out)
plot(match_out, type = "jitter")
plot(summary(match_out))
matched_data <- match.data(match_out)
fit_matched <- glm(
outcome ~ treatment,
family = binomial(),
data = matched_data,
weights = weights
)
Propensity Score Weighting (IPTW)
library(WeightIt)
weights <- weightit(
treatment ~ age + sex + bmi + smoking + comorbidities,
data = df,
method = "ps",
estimand = "ATE"
)
library(cobalt)
bal.tab(weights, stats = c("m", "v"))
love.plot(weights)
library(survey)
design <- svydesign(ids = ~1, weights = ~weights$weights, data = df)
fit_iptw <- svyglm(outcome ~ treatment, design = design, family = binomial())
Doubly Robust Estimation
library(AIPW)
aipw_out <- AIPW$new(
Y = df$outcome,
A = df$treatment,
W = df[, c("age", "sex", "bmi", "smoking")],
Q.SL.library = c("SL.glm", "SL.ranger"),
g.SL.library = c("SL.glm", "SL.ranger"),
k_split = 5,
verbose = FALSE
)$fit()$summary()
Causal Inference
Directed Acyclic Graphs (DAGs)
library(dagitty)
library(ggdag)
dag <- dagitty('
dag {
Exposure -> Outcome
Confounder -> Exposure
Confounder -> Outcome
Mediator -> Outcome
Exposure -> Mediator
}
')
ggdag(dag) + theme_dag()
adjustmentSets(dag, exposure = "Exposure", outcome = "Outcome")
isAdjustmentSet(dag, exposure = "Exposure", outcome = "Outcome",
Z = c("Confounder"))
E-values for Sensitivity Analysis
library(EValue)
evalues.RR(est = 2.5, lo = 1.8, hi = 3.5)
evalues.OR(est = 2.5, lo = 1.8, hi = 3.5, rare = TRUE)
bias_plot(RR = 2.5, xmax = 5)
Instrumental Variables
library(ivreg)
iv_fit <- ivreg(
outcome ~ treatment + covariates | instrument + covariates,
data = df
)
summary(iv_fit, diagnostics = TRUE)
Study Design Calculations
Sample Size for Cohort Studies
library(epiR)
epi.sscohortt(
irexp1 = 0.05,
irexp0 = 0.02,
FT = 5,
n = NA,
power = 0.80,
r = 1,
design = 1,
sided.test = 2,
nfractional = FALSE,
conf.level = 0.95
)
Sample Size for Case-Control Studies
library(epiR)
epi.sscc(
OR = 2.0,
p1 = NA,
p0 = 0.30,
n = NA,
power = 0.80,
r = 1,
phi.coef = 0,
design = 1,
sided.test = 2,
nfractional = FALSE,
conf.level = 0.95,
method = "unmatched",
fleiss = FALSE
)
Outbreak Investigation
Epidemic Curves
library(incidence2)
inc <- incidence(
dates = case_data$onset_date,
interval = "week"
)
plot(inc)
inc_group <- incidence(
dates = case_data$onset_date,
interval = "week",
groups = case_data$region
)
plot(inc_group)
Attack Rates
attack_rates <- df |>
group_by(exposure_variable) |>
summarise(
cases = sum(ill),
total = n(),
attack_rate = cases / total * 100
)
library(fmsb)
riskratio(
exposed_cases, exposed_total,
unexposed_cases, unexposed_total
)
Key Packages Summary
| Package | Purpose |
|---|
| epiR | Epidemiological measures |
| Epi | Person-time, Lexis diagrams |
| epitools | Rate calculations |
| MatchIt | Propensity score matching |
| WeightIt | Propensity score weighting |
| cobalt | Balance diagnostics |
| dagitty, ggdag | Causal diagrams |
| EValue | Sensitivity analysis |
| ivreg | Instrumental variables |
| incidence2 | Epidemic curves |