R coding and Epidemiology
This exam focuses on comprehension, code literacy, and quantitative reasoning rather than rote memorization:
Part 1: R Programming
for loops vs. dplyr, ggplot2 layers).Part 2: Epidemiology
Variable Assignment & Arithmetic
<- to assign/update variables (height <- 1.70).+, -, *, /, ^ (power), %% (modulo).Core Data Types (typeof() / class())
double): Default for numbers (e.g., 54, 1.55).L suffix (e.g., 2L).TRUE or FALSE."Missing", "N/A", "66").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 operatorWhy 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.
| 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.[ ] and [[ ]] in the same expression; it will lead to unexpected errors.if/else & for)& (AND): Both conditions must be TRUE.| (OR): At least one condition must be TRUE.! (NOT): Negates TRUE \(\leftrightarrow\) FALSE.Here are some simple examples of a for loop in R:
You can also iterate over vectors
dplyrdplyrTrue Benefits of dplyr
i in 1:length(...) off-by-one bugs.| >).filter(), group_by(), and summarize().Misconception Check
mutate() does NOT skip rows with NA or automatically impute missing values.filter(!is.na(...)) to remove incomplete rows.ggplot2ggplot2ggplot2 stacks layers using the + operator:
ggplot(data, aes(...)): Sets the dataset and global coordinate mappings (x, y).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.scale_*() & labs(): Customizes labels and ticks. Default scales are generated automatically—scale_x_continuous() is not required for the plot to run.Quick Diagnostic Checklist
non-numeric argument to binary operator:
character).[ ] instead of [[ ]].1, never 0.dplyr: mutate() preserves all rows and propagates NAs unless filtered out.ggplot2 Layers: ggplot() sets axes; + geom_point() draws the points.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}}\]
| 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.
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).
| 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}\).)
Direction & Magnitude
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.”
Review the downloadable Markdown revision notes on Moodle for detailed explanations and self-check examples.