Week 2: Vectors & Subsetting

GPH-GU 2182 · Statistical Programming in R

Yang Feng

2026-09-09

Welcome to Week 2!

Today’s Roadmap: The Backbone of R

Vectors are the fundamental building block of all data structures in R (matrices, data frames, lists).

%%{init: {'theme': 'base', 'themeVariables': { 'fontSize': '16px'}}}%%
flowchart LR
    A["<b>Cycle 1</b><br/>Vector Types &<br/>Coercion Rules"] --> B["<b>Cycle 2</b><br/>Pattern Creation<br/>(seq, rep, %%)"]
    B --> C["<b>Cycle 3</b><br/>Indexing, Filtering<br/>& Mutation"]
    C --> D["<b>Cycle 4</b><br/>Sorting, Ranking &<br/>AI Corner"]
    style A fill:#e8f4f8,stroke:#2980b9,stroke-width:2px
    style B fill:#fef9e7,stroke:#f39c12,stroke-width:2px
    style C fill:#eafaf1,stroke:#27ae60,stroke-width:2px
    style D fill:#f4ecf7,stroke:#8e44ad,stroke-width:2px

Cycle 1
Vector Types &
Coercion Rules

Cycle 2
Pattern Creation
(seq, rep, %%)

Cycle 3
Indexing, Filtering
& Mutation

Cycle 4
Sorting, Ranking &
AI Corner

  • Textbook Reading: R02Pro Chapters 2–3 (r02pro.github.io)
  • Homework 2: Released before class.

Cycle 1: Vector Types & Coercion

The Four Atomic Vector Types

In R, every element in an atomic vector must have the same type:

1. Numeric (Double)

Decimal numbers (default in R):

weights <- c(68.5, 72.0, 81.3)
typeof(weights)
[1] "double"

2. Integer

Explicit whole numbers with L:

counts <- c(1L, 5L, 12L)
typeof(counts)
[1] "integer"

3. Character (Strings)

Text enclosed in quotes:

drugs <- c("aspirin", "statin", "placebo")
typeof(drugs)
[1] "character"

4. Logical (Booleans)

TRUE or FALSE (all caps):

adherent <- c(TRUE, FALSE, TRUE)
typeof(adherent)
[1] "logical"

The Type Hierarchy & Implicit Coercion

What happens when you mix different types in c(...)?

R silently converts everything to the least restrictive type:

\[\text{logical} \longrightarrow \text{integer} \longrightarrow \text{double} \longrightarrow \text{character}\]

# Logical to numeric (TRUE becomes 1, FALSE becomes 0)
sum(c(TRUE, FALSE, TRUE, TRUE))    # count of TRUEs
[1] 3
mean(c(TRUE, FALSE, TRUE, FALSE))  # proportion of TRUEs
[1] 0.5
# Numeric + Character becomes Character
c(10, 25, "missing")
[1] "10"      "25"      "missing"

Coercion in Practice: Prevalence

bp <- c(150, 128, 142, NA, 135, 118)
bp > 140
[1]  TRUE FALSE  TRUE    NA FALSE FALSE
mean(bp > 140, na.rm = TRUE)
[1] 0.4

Pro-Tip for Health Data

mean(bp > 140, na.rm = TRUE) directly calculates the prevalence of hypertension by coercing logicals to 1s and 0s!

Summary Statistics on Vectors

R has built-in vector aggregators:

chol <- c(185, 220, 240, 195, 210, NA)
length(chol)      # counts the NA
[1] 6
sum(is.na(chol))  # missing values
[1] 1
mean(chol, na.rm = TRUE)
[1] 210
sd(chol, na.rm = TRUE)
[1] 21.50581
summary(chol)             # 5-number summary + mean + NAs
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
    185     195     210     210     220     240       1 

💻 In-Class Exercise 2A (12 min)

Paired Hands-on Exercise

  1. Open RStudio and your week-02-inclass.qmd worksheet.
  2. Predict the typeof() and value of:
    • c(4, 7, FALSE)
    • c(3L, 5.5, "control")
    • c(TRUE, FALSE) + 5
  3. A clinical trial enrolled 8 patients with viral loads: 1200, 450, 0, 8900, 320, 0, 1500, 60. Calculate the proportion of patients with undetectable viral load (viral_load == 0) using mean().

Cycle 2: Creating Patterned Vectors

Sequences with : and seq()

Instead of typing numbers manually, generate sequences automatically:

The Colon Operator :

Consecutive integer sequences:

1:10
 [1]  1  2  3  4  5  6  7  8  9 10
20:15    # Counts backward!
[1] 20 19 18 17 16 15
-3:3
[1] -3 -2 -1  0  1  2  3

The seq() Function

Flexible step sizes & lengths:

# By step size
seq(from = 0, to = 100, by = 20)
[1]   0  20  40  60  80 100
# By total length
seq(from = 0, to = 1, length.out = 5)
[1] 0.00 0.25 0.50 0.75 1.00

Repetition with rep()

The rep() function replicates values using times or each:

times (Pattern repetition)

Repeats the whole vector:

rep(c("A", "B"), times = 3)
[1] "A" "B" "A" "B" "A" "B"
# Unequal repetitions per element:
rep(c("Control", "Treated"), times = c(4, 2))
[1] "Control" "Control" "Control" "Control" "Treated" "Treated"

each (Element repetition)

Repeats each item before moving to next:

rep(c("A", "B"), each = 3)
[1] "A" "A" "A" "B" "B" "B"
# Combining both:
rep(c("Dose1", "Dose2"), each = 2, times = 2)
[1] "Dose1" "Dose1" "Dose2" "Dose2" "Dose1" "Dose1" "Dose2" "Dose2"

Modulo Arithmetic %%

The modulo operator %% calculates the remainder of division:

14 %% 3   # remainder of 14 / 3
[1] 2
10 %% 2   # 10 is even
[1] 0

Common Applications in Data Science

  • Even numbers: x %% 2 == 0
  • Divisible by 5: x %% 5 == 0
  • Assigning participants to \(K\) rotating study groups: (1:N) %% K + 1

💻 In-Class Exercise 2B (12 min)

Paired Hands-on Exercise

  1. Create a sequence of drug dosing times from hour 0 to hour 72 spaced every 8 hours using seq().
  2. Generate study cohort labels for 12 participants: 4 “Control”, 4 “Low-Dose”, and 4 “High-Dose” using rep().
  3. Given numbers <- 1:50, extract all numbers that are multiples of 7 using %%.

Cycle 3: Subsetting & Mutating Vectors

The Three Subsetting Methods

We extract elements using square brackets x[...]:

ages <- c(23, 45, 19, 31, 56, 42)

1. Positive Indices

Extract by position (1-indexed):

ages[1]
[1] 23
ages[c(1, 4)]
[1] 23 31
ages[2:4]
[1] 45 19 31

2. Negative Indices

Exclude specific positions:

ages[-1]
[1] 45 19 31 56 42
ages[-c(2, 5)]
[1] 23 19 31 42

ages[-2:4] is an error: write ages[-(2:4)].

3. Logical Subsetting

Extract where TRUE:

ages[ages > 40]
[1] 45 56 42
ages[ages >= 30 & ages <= 50]
[1] 45 31 42

Logical Operators for Filtering

Combine conditions using element-wise logical operators:

Operator Meaning Example
& Element-wise AND (both true) (bmi > 25) & (age > 50)
\| Element-wise OR (either true) (status == "Severe") \| (fever == TRUE)
! Logical NOT (inversion) !(city %in% c("NY", "CA"))
%in% Value matching (set membership) id %in% confirmed_cases
sbp <- c(118, 142, 135, 160, 122)
stage2_htn <- sbp >= 140
sbp[stage2_htn]
[1] 142 160

Modifying Vectors in Place (Mutation)

Use subsetting on the left side of <- to update specific elements:

scores <- c(88, -99, 95, -99, 72)

# Replace survey code -99 with NA:
scores[scores == -99] <- NA
scores
[1] 88 NA 95 NA 72
# Cap values at 90 (winsorizing):
scores[scores > 90 & !is.na(scores)] <- 90
scores
[1] 88 NA 90 NA 72

💻 In-Class Exercise 2C (15 min)

Paired Hands-on Exercise

Given the patient glucose vector:

glucose <- c(95, 142, 180, 88, 210, 115, -1, 104)
  1. Extract the glucose readings that are in the pre-diabetes range (\(100 \le \text{glucose} \le 125\)).
  2. Patient 7 was miscoded as -1. Replace all negative values with NA.
  3. Extract all valid readings (ignoring NA) that indicate diabetes (\(\text{glucose} \ge 126\)).

Cycle 4: Sorting, Ranking & AI Corner

Sorting, Ranking, and Ordering

Understanding the difference between sort(), rank(), and order():

vals <- c(30, 10, 50, 20)

sort(x)

Returns sorted values:

sort(vals)
[1] 10 20 30 50
sort(vals, decreasing = TRUE)
[1] 50 30 20 10

rank(x)

Returns rank position of each element:

rank(vals)
[1] 3 1 4 2

vals[1] is 30, the 3rd smallest, so its rank is 3.

order(x)

Returns indices that would sort x:

order(vals)
[1] 2 4 1 3
vals[order(vals)] # sorted!
[1] 10 20 30 50

Handling Ties in rank()

When numbers repeat, how should ranks be assigned?

scores <- c(80, 95, 80, 70)

rank(scores)                        # Default: average ranks
[1] 2.5 4.0 2.5 1.0
rank(scores, ties.method = "first") # By appearance
[1] 2 4 3 1
rank(scores, ties.method = "min")   # Sports ranking
[1] 2 4 2 1

Tip

ties.method = "first" is essential for deterministic top-\(K\) rankings in data pipelines!

AI Corner: Beware Vector Recycling!

When R operates on vectors of different lengths, it silently recycles the shorter one:

What R Does:

x <- c(10, 20, 30, 40)
y <- c(1, 2)
x + y   # 10+1, 20+2, 30+1, 40+2
[1] 11 22 31 42

⚠️ The Danger with AI:

  • LLMs often generate code that accidentally recycles vectors when filtering or standardizing.
  • Always check length(x) == length(y) before element-wise operations!

Summary & Week 2 Checklist

  1. Submit Homework 1 on GitHub.
  2. Weekly Exercise 2: Released on GitHub; due date on the course website.
  3. Finish & Push In-Class 2: Push your rendered week-02-inclass.html for participation credit.
  4. Upcoming in Week 3: Matrices, Lists, Data Frames + In-Class Quiz 1 (20 min, Weeks 1–2).