Week 3: Matrices, Lists, Data Frames & Data Import

GPH-GU 2182: Statistical Programming in R · Fall 2026

Yang Feng, PhD

New York University · School of Global Public Health

2026-09-16

Welcome to Week 3!

Today's Roadmap

  1. Matrices & 2D Indexing: 2D homogeneous data, row/col operations.
  2. Lists: Storing heterogeneous objects of different types & lengths.
  3. Data Frames & Tibbles: The cornerstone of statistical data in R.
  4. Data Import & Export: Loading real-world CSV & Excel files into R.
  5. AI Corner: Debugging messy imports & type-parsing traps.

Today's Milestones

  • Homework 3: Released today (Matrices, Lists, Data Frames & Import).
  • 📝 Quiz 1 (Weeks 1–2): Administered during the last 30 minutes of class. Closed-book, paper handout.

Cycle 1: Matrices & 2D Indexing

What is a Matrix?

A matrix is a 2-dimensional collection of elements of the same basic type (homogeneous), arranged in rows and columns.

Column-by-Column (Default)

m1 <- matrix(1:6, nrow = 2, ncol = 3)
m1
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Row-by-Row (byrow = TRUE)

m2 <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)
m2
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Dimensions & Naming

dim(m2)    # c(number_of_rows, number_of_columns)
[1] 2 3
nrow(m2)
[1] 2
ncol(m2)
[1] 3
# Adding Row and Column Names
rownames(m2) <- c("Hospital_A", "Hospital_B")
colnames(m2) <- c("ICU_Beds", "Ventilators", "Nurses")
m2
           ICU_Beds Ventilators Nurses
Hospital_A        1           2      3
Hospital_B        4           5      6

2D Matrix Subsetting: [row, column]

Always remember: [row, column] (think “RC Cola” or “Roman Catholic”).

# 1. Single element: row 1, col 2
m2[1, 2]
[1] 2
# 2. Entire row: leave column blank!
m2[1, ]
   ICU_Beds Ventilators      Nurses 
          1           2           3 
# 3. Entire column: leave row blank!
m2[, "ICU_Beds"]
Hospital_A Hospital_B 
         1          4 

Submatrices & Conditional Replacement

# 4. Submatrix: rows 1:2, columns 2:3
m2[1:2, 2:3]
           Ventilators Nurses
Hospital_A           2      3
Hospital_B           5      6
# 5. Conditional replacement
m2[m2 < 3] <- 0
m2
           ICU_Beds Ventilators Nurses
Hospital_A        0           0      3
Hospital_B        4           5      6

👥 Paired Exercise 1: ICU Capacity Matrix (10 min)

Task

In your week-03-inclass.qmd worksheet:

  1. Construct a 3x3 matrix icu_admissions containing the numbers c(12, 18, 5, 24, 30, 11, 8, 15, 4) filled row-by-row.
  2. Assign rownames: c("Mon", "Tue", "Wed") and colnames: c("Site_1", "Site_2", "Site_3").
  3. Compute the total admissions per site using colSums(icu_admissions).
  4. Extract all days where Site_2 admissions exceeded 15.

Expected Output

      Site_1 Site_2 Site_3
Mon       12     18      5
Tue       24     30     11
Wed        8     15      4

Site totals:
Site_1: 44, Site_2: 63, Site_3: 20

Time Remaining: 10 minutes.

Cycle 2: Lists & Heterogeneous Data

Why Do We Need Lists?

Vectors and matrices are homogeneous (all elements must be the exact same type).

In public health and clinical research, real records contain heterogeneous data:

  • Patient ID (character)
  • Demographics (character, numeric)
  • Blood pressure readings across multiple visits (numeric vector of length 5)
  • Lab test results (logical or nested sub-records)

A list is a flexible container whose elements can be of any type, length, or structure!

Creating & Inspecting Lists

patient_record <- list(
  id = "PT-84920",
  age = 54,
  smoker = FALSE,
  sbp_history = c(138, 142, 130, 128, 135),
  metadata = list(clinic = "Bellevue", enrolled = "2026-01-15")
)

# Inspect structure
str(patient_record)
List of 5
 $ id         : chr "PT-84920"
 $ age        : num 54
 $ smoker     : logi FALSE
 $ sbp_history: num [1:5] 138 142 130 128 135
 $ metadata   :List of 2
  ..$ clinic  : chr "Bellevue"
  ..$ enrolled: chr "2026-01-15"

The Crucial Difference: $ vs [[ ]] vs [ ]

1. $ or [[ ]] (Extract Contents)

Extracts the raw object inside (here a numeric vector, so math works):

patient_record$sbp_history
[1] 138 142 130 128 135
patient_record[["sbp_history"]]
[1] 138 142 130 128 135
mean(patient_record$sbp_history)
[1] 134.6

2. [ ] (Sub-list / Slice)

Returns a smaller list containing that compartment:

# Returns a LIST of length 1
sub_list <- patient_record[4]
typeof(sub_list)
[1] "list"
# mean(sub_list) WILL FAIL!
# Lists cannot be averaged directly.

Think of a list as a train with cargo cars. [4] gives you the 4th car; [[4]] opens the car and gives you the cargo inside!

👥 Paired Exercise 2: Patient Trial List (10 min)

Task

In week-03-inclass.qmd:

  1. Build a list study_subject containing:
    • name: "Jordan Lee"
    • arm: "Treatment_A"
    • viral_loads: c(45000, 12000, 850, 40)
    • adverse_events: 0
  2. Extract the viral_loads vector and calculate the percentage reduction from baseline (visit 1 to visit 4).
  3. Add a new element to the list named completed set to TRUE.

Expected Output

Baseline: 45000
Final: 40
Reduction: 99.91%

$completed
[1] TRUE

Time Remaining: 10 minutes.

Cycle 3: Data Frames & Tibbles

Data Frames: The Heart of Data Analysis

A data frame is a list of equal-length vectors. Each column is a variable; each row is an observation.

# Creating a data frame
cohort <- data.frame(
  id = c("P01", "P02", "P03", "P04", "P05"),
  age = c(45, 62, 38, 71, 55),
  bmi = c(24.2, 31.0, 27.5, 29.8, 22.1),
  diabetes = c(FALSE, TRUE, FALSE, TRUE, FALSE),
  stringsAsFactors = FALSE
)

# Inspecting
nrow(cohort)       # observations
[1] 5
ncol(cohort)       # variables
[1] 4

Summarizing a Data Frame

summary(cohort)    # Summary statistics for each column
      id                 age            bmi         diabetes      
 Length:5           Min.   :38.0   Min.   :22.10   Mode :logical  
 Class :character   1st Qu.:45.0   1st Qu.:24.20   FALSE:3        
 Mode  :character   Median :55.0   Median :27.50   TRUE :2        
                    Mean   :54.2   Mean   :26.92                  
                    3rd Qu.:62.0   3rd Qu.:29.80                  
                    Max.   :71.0   Max.   :31.00                  

Tibbles vs. Base Data Frames

A tibble (tibble::tibble()) is a modern data frame with refined behavior:

Base data.frame

  • Prints all rows and columns to console (can flood screen).
  • May coerce strings or drop dimensions unpredictably (df[, 1] becomes a vector).
  • Partial name matching (df$d might match df$diabetes).

tibble (library(tibble))

  • Clean printing: shows top 10 rows and variable types (<chr>, <dbl>, <lgl>).
  • Strict subsetting: tb[, 1] always stays a tibble.
  • Never coerces types or uses partial matching.

Subsetting & Filtering Data Frames

# 1. Accessing columns
cohort$bmi
[1] 24.2 31.0 27.5 29.8 22.1
cohort[["age"]]
[1] 45 62 38 71 55
# 2. Creating a new computed column
cohort$bmi_high <- cohort$bmi >= 30.0
cohort
   id age  bmi diabetes bmi_high
1 P01  45 24.2    FALSE    FALSE
2 P02  62 31.0     TRUE     TRUE
3 P03  38 27.5    FALSE    FALSE
4 P04  71 29.8     TRUE    FALSE
5 P05  55 22.1    FALSE    FALSE

Filtering Rows of a Data Frame

# 3. Filtering rows by condition: df[condition, ]
seniors <- cohort[cohort$age >= 60, ]
seniors
   id age  bmi diabetes bmi_high
2 P02  62 31.0     TRUE     TRUE
4 P04  71 29.8     TRUE    FALSE
# 4. Complex filtering: BMI > 25 AND non-diabetic
overweight_non_diab <- cohort[cohort$bmi > 25 & !cohort$diabetes, ]
overweight_non_diab
   id age  bmi diabetes bmi_high
3 P03  38 27.5    FALSE    FALSE

👥 Paired Exercise 3: Cohort Filtering (10 min)

Task

In week-03-inclass.qmd:

  1. Use the provided patients data frame.
  2. Add a new column pulse_pressure computed as sbp - dbp.
  3. Filter all patients who meet both criteria:
    • Age >= 50
    • pulse_pressure > 45
  4. Calculate the average bmi of this high-risk sub-cohort.

Hints

  • Remember the comma after row condition: patients[condition, ]
  • Use mean(..., na.rm = TRUE) if missing values exist.

Cycle 4: Data Import & Export

Importing Real Data (CSV & Excel)

1. Reading CSV Files (readr)

library(readr)

# read_csv() returns a clean tibble
nhanes_data <- read_csv(
  "data/nhanes_sample.csv",
  na = c("", "NA", "999", "Unknown")
)

head(nhanes_data)

2. Reading Excel (readxl)

library(readxl)

# Check available sheets
excel_sheets("data/clinical_trial.xlsx")

# Read specific sheet
trial_data <- read_excel(
  "data/clinical_trial.xlsx",
  sheet = "Baseline_Vitals",
  na = "NA"
)

Exporting Cleaned Datasets

Once your data is cleaned and validated, save it back to disk:

# Exporting to CSV
write_csv(cohort, "data/cleaned_cohort.csv")

# Saving R binary objects (.rds preserves exact data types!)
saveRDS(cohort, "data/cleaned_cohort.rds")
restored_cohort <- readRDS("data/cleaned_cohort.rds")

AI Corner: The Silent Import Bug

The “Unknown” String Trap

❌ What AI Generated

# Prompt: "Read this BP dataset"
bp_df <- read.csv("bp_data.csv")
mean(bp_df$systolic)
[1] NA
class(bp_df$systolic)
[1] "character"

Why? Row 42 holds "Unknown", so read.csv made the whole column character!

✅ The Verified Fix

Always specify explicit na strings upon import:

library(readr)
bp_df <- read_csv(
  "bp_data.csv",
  na = c("", "NA", "Unknown", "-99")
)
spec(bp_df)   # verify column types
cols(
  id = col_double(),
  systolic = col_double()
)
mean(bp_df$systolic, na.rm = TRUE)
[1] 128.3878

In-Class Quiz 1

📝 Quiz 1 Instructions

  1. Laptops, tablets, and phones away.
  2. This is an individual, closed-book, paper-based quiz covering Weeks 1–2.
  3. You have 20 minutes.
  4. Hand your paper to the teaching team when time is called.
  5. We will show the answer key on screen right after collection!

Note

Remember: Your lowest quiz score of the semester is automatically dropped!