Exam revision

R coding and Epidemiology

Dr. Yu Cheng Hsu

Exam Design Philosophy & Strategy

This exam focuses on comprehension, code literacy, and quantitative reasoning rather than rote memorization:

Part 1: R Programming

  • Code Literacy: Tracing execution step-by-step.
  • Debugging: Diagnosing why a snippet fails or throws an error.
  • Tool Selection: Understanding trade-offs (for loops vs. dplyr, ggplot2 layers).

Part 2: Epidemiology

  • Design Comparison: Differentiate different kind of study design.
  • Metric Selection: Justifying Relative Risk (RR) vs. Odds Ratio (OR).
  • Calculation & Interpretation: Computing from \(2 \times 2\) tables and writing accurate clinical statements.

Part 1: Introductory R Programming

1. Fundamentals & Data Types

Variable Assignment & Arithmetic

  • Use <- to assign/update variables (height <- 1.70).
  • Operators: +, -, *, /, ^ (power), %% (modulo).

Core Data Types (typeof() / class())

  1. Numeric (double): Default for numbers (e.g., 54, 1.55).
  2. Integer: Whole numbers with L suffix (e.g., 2L).
  3. Logical: TRUE or FALSE.
  4. Character: Text strings in quotes (e.g., "Missing", "N/A", "66").

Implicit Type Coercion in Vectors

Atomic vectors must be homogeneous (all elements share one data type). Mixing types triggers automatic coercion:

\[\text{logical} < \text{integer} < \text{numeric} < \text{character}\]

Common Debugging Trap

weights <- c(54, "66", 78, "Missing")
fat_weight <- c(20 17, "N/A", 19)

body_fat_ratio <- weights[2] / (fat_weight[2])
# Error in (heights[2])^2 : non-numeric argument to binary operator

Why does this fail?
Even though 29 was entered without quotes, "N/A" coerces the entire fat_weight vector into character strings ("20", "17", "N/A", "19"). Arithmetic operations cannot run on character strings.

2. Data Structures & Subsetting

Data Structures

Structure Dimensions Homogeneity Key Subsetting Syntax
Vector 1D Same type only vec[i] (1-based indexing; starts at 1)
Matrix 2D Same type only mat[row, col]
List 1D Mixed types allowed list[[i]] or list$name (value); list[i] (sub-list)
Data Frame 2D Columns can differ; each column is a vector df$col, df[row, col]
  • LIST[[1]] extracts the raw numeric scalar, allowing arithmetic operations.
  • Do not mix [ ] and [[ ]] in the same expression; it will lead to unexpected errors.

3. Operators & Control Flow (if/else & for)

Logical Operators

  • & (AND): Both conditions must be TRUE.
  • | (OR): At least one condition must be TRUE.
  • ! (NOT): Negates TRUE \(\leftrightarrow\) FALSE.

For loops

  • Using loop to reduce redundant code

Here are some simple examples of a for loop in R:

# examples of loop
# Loop printing a series of numbers from 1 to 10
for (i in 1:10){
  print(i)
}

You can also iterate over vectors

# Loop printing a vector of names
names <- c("Jason","Ray","Yuanhua")
for (i in names){
  print(i)
}

4. Data Wrangling with dplyr

Using dplyr

library(dplyr)

result <- patient_df |>
  mutate(bmi = weight / height^2)

True Benefits of dplyr

  • No index tracking: Eliminates i in 1:length(...) off-by-one bugs.
  • Vectorized & readable: Concise left-to-right pipelines (| >).
  • Composable: Connects directly to filter(), group_by(), and summarize().

Misconception Check

  • mutate() does NOT skip rows with NA or automatically impute missing values.
  • Use filter(!is.na(...)) to remove incomplete rows.

5. Data Visualization with ggplot2

Using ggplot2

ggplot2 stacks layers using the + operator:

library(ggplot2)
ggplot(result, aes(x = height, y = weight)) +
  geom_point()
  1. ggplot(data, aes(...)): Sets the dataset and global coordinate mappings (x, y).
  2. geom_*(): Inherits global aes() mappings automatically:
    • geom_point() \(\rightarrow\) Scatter plot (individual points).
    • geom_line() \(\rightarrow\) Line chart; geom_histogram() / geom_boxplot() \(\rightarrow\) Distributions; geom_bar() \(\rightarrow\) Categorical counts.
  3. scale_*() & labs(): Customizes labels and ticks. Default scales are generated automatically—scale_x_continuous() is not required for the plot to run.

R Pre-Exam Troubleshooting Summary

Quick Diagnostic Checklist

  1. non-numeric argument to binary operator:
    • Check if a vector has a string mixed in (coercing all elements to character).
    • Check if a list was subsetted with [ ] instead of [[ ]].
  2. 1-Based Indexing: The first item in R is always index 1, never 0.
  3. Missing Values in dplyr: mutate() preserves all rows and propagates NAs unless filtered out.
  4. ggplot2 Layers: ggplot() sets axes; + geom_point() draws the points.

Part 2: Epidemiology

1. Categories of Epidemiological Studies

  • Descriptive Epidemiology: Examines disease distribution by person, place, and time.
    • Case study / series: Detailed patient profiles.
    • Cross-sectional study: Snapshot of disease prevalence and exposures at one point in time.
    • Ecological study: Population-level aggregate records/registries.
  • Analytic Epidemiology (Observational): Tests exposure–outcome hypotheses without investigator intervention (Cohort & Case-Control).
  • Experimental Epidemiology: Investigator assigns intervention/exposure randomly (Randomized Controlled Trials / RCTs).

2. Measures of Disease Frequency

Prevalence vs. Incidence

\[\text{Prevalence} = \frac{\text{All existing cases (new + old) at a specific time}}{\text{Total population at that specific time}}\]

\[\text{Risk (Cumulative Incidence)} = \frac{\text{New cases arising during a defined period}}{\text{Total population at risk at the start of the period}}\]

  • Key Distinction: Prevalence measures existing burden; Incidence measures new disease occurrence over time.

3. Cohort vs. Case-Control Study Designs

Feature Cohort Study Case-Control Study
Starting Point Exposure status Outcome (disease) status
Direction of Inquiry Forward (Exposure \(\rightarrow\) Outcome) Backward (Outcome \(\rightarrow\) Exposure)
Measures Incidence? Yes No
Primary Metric Relative Risk (RR) Odds Ratio (OR)
Best Suited For Rare exposures; multiple outcomes Rare diseases; long latency periods
Main Vulnerabilities Loss to follow-up (attrition), high cost Recall bias, control selection bias

Note on Retrospective Cohort Studies: Even when using past medical records, researchers still start by classifying past exposure and tracking forward to see who later developed the disease.

Why Relative Risk (RR) Fails in Case-Control Studies

Essential Exam Concept

In a case-control study, researchers select a predetermined number of cases and controls (e.g., 1,000 cancer cases and 1,000 healthy controls).

  • Because the case-to-control ratio is artificially controlled by the study design, baseline disease incidence (risk) cannot be estimated from the table.
  • Therefore, Relative Risk (RR) is not applicable, and the Odds Ratio (OR) must be used instead.

4. \(2 \times 2\) Contingency Table & Formulas

Exposure Status Developed Outcome (Cases) Did Not Develop Outcome (Controls) Total
Exposed \(a\) \(b\) \(a + b\)
Unexposed \(c\) \(d\) \(c + d\)
Total \(a + c\) \(b + d\) \(a + b + c + d\)

Cohort Study: Relative Risk (RR) \[ \small \text{Risk}_{\text{exposed}} = \frac{a}{a+b}, \quad \text{Risk}_{\text{unexposed}} = \frac{c}{c+d} \]

\[\small \text{RR} = \frac{a / (a+b)}{c / (c+d)} \]

Case-Control Study: Odds Ratio (OR)

\[ \small \text{Odds}_{\text{cases}} = \frac{a}{c}, \quad \text{Odds}_{\text{controls}} = \frac{b}{d} \]

\[ \small \text{OR} = \frac{a / c}{b / d} = \frac{a \times d}{b \times c} \]

(Under the rare disease assumption, where \(a \ll b\) and \(c \ll d\), \(\text{OR} \approx \text{RR}\).)

5. Interpreting RR and OR

Direction & Magnitude

  • \(\text{RR} = 1\) or \(\text{OR} = 1\): Null value — no association between exposure and outcome.
  • \(\text{RR} > 1\) or \(\text{OR} > 1\): Positive association — higher risk/odds of outcome in exposed group.
  • \(\text{RR} < 1\) or \(\text{OR} < 1\): Negative (inverse) association — lower risk/odds in exposed group (protective).

Short-Answer Exam Checklist

  1. Comparison Groups: State both groups clearly (e.g., stroke cases vs. disease-free controls).
  2. Exact Metric Language: Use “times the odds” for OR (never say “times the risk” or “times more likely”).
  3. Direction: Explicitly state positive or negative association.

Example (\(\text{OR} = 2.11\)): “Patients who developed a stroke had 2.11 times the odds of being alcohol users compared to controls who did not develop a stroke, indicating a positive association between alcohol use and stroke.”

6. Hierarchy of Epidemiological Evidence

  1. Randomized Controlled Trials (RCTs): Highest internal validity; random allocation controls confounding.
  2. Cohort Studies: Establishes clear temporal sequence (exposure precedes outcome).
  3. Case-Control Studies: Efficient for rare diseases, vulnerable to recall and selection bias.
  4. Case Reports & Case Series: Hypothesis-generating only; lacks a comparison group.

Good Luck on Your Exam!

Review the downloadable Markdown revision notes on Moodle for detailed explanations and self-check examples.