Lesson 9 of 17 · Week 04 · Tue Oct 20
Vectorization
Questions
- How can I operate on all the elements of a vector at once?
Objectives
- Compute new columns from existing ones without loops.
- Predict how R recycles a shorter vector, including in a matrix.
- Use logical vectors with
sum(),mean()andifelse(). - Write a mathematical sum in one vectorized line.
One operation, every element
Most R functions and operators work on whole vectors at once, element by element. You don't need a loop:
x <- 1:5
x * 2 # 2 4 6 8 10
x + c(10, 20, 30, 40, 50)
log10(c(10, 100, 1000))
gm$pop / 1e6 # every row's population, in millions
Vectorized code is shorter, easier to read, and much faster than the equivalent loop. It's one of the most important habits to build in R.
Adapted from Software Carpentry's “Vectorization” episode (CC BY 4.0, The Carpentries). Text, examples and exercises have been rewritten for this course.
New columns in one line
gm$gdp_billions <- gm$pop * gm$gdpPercap / 1e9 # total GDP, every row at once
head(gm)
Operations between two columns pair up row 1 with row 1, row 2 with row 2, and so on.
Recycling
When the two vectors have different lengths, R recycles the shorter one: it starts again from the beginning until it has covered the longer vector. If the longer length isn't a multiple of the shorter one, you get a warning.
1:6 * c(1, -1) # 1 -2 3 -4 5 -6
1:6 + c(100, 200, 300) # 101 202 303 104 205 306
1:5 * c(1, 10) # works, but warns: 5 is not a multiple of 2
A matrix is a vector with dimensions, stored column by column, so a recycled vector runs down the columns:
m <- matrix(1:6, nrow = 2)
m * c(1, -1) # row 1 times 1, row 2 times -1
m %*% t(m) # true matrix multiplication (rarely needed in this course)
Comparisons and logic are vectorized too
gm$lifeExp > 70 # one TRUE/FALSE per row
sum(gm$lifeExp > 70) # how many (TRUE counts as 1)
mean(gm$lifeExp > 70) # what proportion
ifelse(gm$lifeExp > 70, "long", "short")
& and | work element by element; && and || expect a single value
and are for if() conditions. any() and all() reduce a logical vector to one value.
Functions that summarise a whole vector
sum(), mean(), prod(), cumsum(), max()… take a whole vector.
Combine them with vectorized arithmetic to compute a formula in one line. For example,
1 + 1/2 + 1/4 + … + 1/210:
sum(1 / 2 ^ (0:10))
Exercises
Each exercise gives you up to 10 checked attempts. Use Run as many times as you like to experiment first, then click Check answer when you're ready. Your exercises use numbers/subsets unique to you, so answers won't match a classmate's exactly.
Exercise 1 — Total GDP in billions
0 / 10 attempts usedAdd a column gdp_billions to gm: each row's total GDP (population × GDP per capita) in
billions of dollars, in one vectorized line. Check it with head(gm).
Exercise 2 — Plot it: all, then three
0 / 10 attempts usedUsing the gdp_billions column (already added for you here), make two plots of total GDP against year with
one line per country (group = country):
p_all: all countries;p_three: only the three countries shown when you click Run, stored inthree. Subset with%in%before plotting.
Exercise 3 — Recycling in a matrix
0 / 10 attempts usedClick Run to see a matrix m and four expressions. Without running them,
predict the value in row 2, column 3 of each result and store your four predictions, in order, in
answers. Then run each expression to check. Where did recycling surprise you?
Exercise 4 — A series in one line
0 / 10 attempts usedThe alternating series 1 − 1/2 + 1/3 − 1/4 + … slowly approaches log(2). Using vectorization (no loop), compute
the sum of its first n1 terms in s1 and of its first n2 terms in s2
(click Run for your values). How close does each get to log(2)?
Key Points
- Arithmetic, comparisons and most functions work element by element on whole vectors.
- A shorter vector is recycled; lengths that don't divide evenly give a warning.
- Matrices recycle down the columns.
sum(condition)counts andmean(condition)gives a proportion.
Proof of completion
Once you've attempted every exercise above, download a PDF summary of your work on this lesson — your name, the exercises you passed, attempt counts, timing, and your final code for each.