Skip to content
LumenaryAcademy
Foundations 55 min

Vectors and vectorisation

The data structure under everything in R, arithmetic on whole vectors at once, recycling, logical vectors, and the four ways to index.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

Thinking in whole columns

Suppose you have the daily temperatures for a month and want them in Fahrenheit. In most languages you would write a loop: for each temperature, multiply by 9, divide by 5, add 32, append to a new list. In R you write temps * 9 / 5 + 32, and the arithmetic is applied to every element at once. This is vectorisation, and it is the single most important idea in the language.

It is not only shorter. Vectorised operations run in compiled C code inside R, so they are typically many times faster than an R loop doing the same work. More importantly, they change how you think. Instead of "for each row, if the score is at least 60, add one to a counter", you think "the scores that are at least 60" and "how many of them": sum(scores >= 60). Experienced R users read and write code at this level all day, and code written this way is easier to check because there are fewer moving parts.

This lesson builds that habit: how vectors are made, how arithmetic and comparisons work on them, how R lines up vectors of different lengths, and how to pick out the elements you want.

DefinitionsH

What a vector is

Definition— Atomic vector

An atomic vector is an ordered sequence of elements that all have the same type: logical, integer, double, character (and, rarely, complex or raw). It has a length, possibly zero, and may carry names, one per element. A single number such as 5 is simply a vector of length one.

There is no separate "scalar" type in R, which is why every result prints with [1]. The next lesson explores the types; this one is about what all vectors have in common. The common ways to make one:

CodeResult
c(21.5, 23, 19.8)combine values into a vector
1:5the integers 1, 2, 3, 4, 5 (also 5:1 counting down)
seq(0, 100, by = 25)0, 25, 50, 75, 100
seq(0, 1, length.out = 5)five evenly spaced values from 0 to 1
rep(c("am", "pm"), times = 3)"am" "pm" "am" "pm" "am" "pm"
numeric(3), character(2)vectors of zeros or empty strings, ready to fill
r
# Five ways to make a vector.
temps <- c(21.5, 23.0, 19.8, 25.1, 22.4)   # combine values
days  <- 1:5                               # a sequence of integers
seq(0, 100, by = 25)                       # a sequence with a step
seq(0, 1, length.out = 5)                  # a sequence with a given length
rep(c("am", "pm"), times = 3)              # repetition

# Arithmetic is element by element.
temps * 9 / 5 + 32                         # Celsius to Fahrenheit
temps - mean(temps)                        # distance from the mean
days^2

# Two vectors of the same length combine pairwise.
rain_mm  <- c(0, 4, 12, 0, 1)
rain_hrs <- c(0, 1, 3, 0, 0.5)
rain_mm / rain_hrs                         # 0 / 0 is NaN

# Many functions summarise or transform a whole vector.
length(temps); sum(temps); range(temps)
cumsum(rain_mm)
diff(temps)
sort(temps, decreasing = TRUE)
text
[1]   0  25  50  75 100
[1] 0.00 0.25 0.50 0.75 1.00
[1] "am" "pm" "am" "pm" "am" "pm"
[1] 70.70 73.40 67.64 77.18 72.32
[1] -0.86  0.64 -2.56  2.74  0.04
[1]  1  4  9 16 25
[1] NaN   4   4 NaN   2
[1] 5
[1] 111.8
[1] 19.8 25.1
[1]  0  4 16 16 17
[1]  1.5 -3.2  5.3 -2.7
[1] 25.1 23.0 22.4 21.5 19.8

temps - mean(temps) subtracts a single number from every element, the first step of many statistical calculations. Dividing rainfall by hours gave the intensity per hour, and the two dry days, where both values are zero, gave NaN, "not a number", because 0 / 0 has no meaningful value. (A non-zero number divided by zero gives Inf or -Inf.) The semicolons let three short expressions share a line; each is still printed separately.

The summarising functions fall into two families. Some reduce a vector to one value: sum, mean, median, min, max, length, sd. Others return a vector of the same or related length: cumsum (running totals), diff (differences between neighbours, one fewer element), sort, rev, round. Knowing which family a function belongs to tells you what shape of result to expect.

IntuitionH

Recycling and logical vectors

What happens when two vectors of different lengths meet in an arithmetic expression? R recycles the shorter one: it repeats it from the beginning until it is as long as the longer one. That is what makes temps * 2 work, since 2 is a vector of length one recycled five times. It also means c(10, 20, 30, 40) + c(1, 2) adds 1, 2, 1, 2. If the longer length is not a multiple of the shorter, R still recycles but issues a warning, because that is almost always a mistake.

Comparisons are vectorised too. scores >= 60 compares every score with 60 and returns a logical vector of TRUE and FALSE. Logical vectors are the workhorse of data analysis in R, because so many questions are of the form "which elements satisfy this condition?", and R gives you the tools to answer them:

  • sum(cond) counts the TRUE values, and mean(cond) gives their proportion, because TRUE counts as 1 and FALSE as 0 in arithmetic.
  • which(cond) returns the positions of the TRUE values.
  • any(cond) and all(cond) reduce a logical vector to one answer.
  • & (and), | (or) and ! (not) combine logical vectors element by element.
  • x %in% y asks, for each element of x, whether it appears anywhere in y.
r
# Recycling: the shorter vector is repeated to match the longer one.
c(10, 20, 30, 40) + c(1, 2)
c(10, 20, 30, 40) * 2          # a "scalar" is a vector of length 1, recycled

# If the longer length is not a multiple of the shorter, R warns.
# Here we catch the warning and print its message instead of stopping.
tryCatch(c(10, 20, 30) + c(1, 2),
         warning = function(w) conditionMessage(w))

# Comparisons are vectorised too, and give logical vectors.
scores <- c(Amina = 72, Bao = 45, Carlos = 88, Divya = 59, Emeka = 91)
scores >= 60
sum(scores >= 60)              # how many passed
mean(scores >= 60)             # what fraction passed
which(scores >= 60)            # where (by position, with names)
any(scores > 90); all(scores > 40)

# & and | combine logical vectors element by element.
scores >= 50 & scores < 80
c("Bao", "Zainab") %in% names(scores)
text
[1] 11 22 31 42
[1] 20 40 60 80
[1] "longer object length is not a multiple of shorter object length"
 Amina    Bao Carlos  Divya  Emeka
  TRUE  FALSE   TRUE  FALSE   TRUE
[1] 3
[1] 0.6
 Amina Carlos  Emeka
     1      3      5
[1] TRUE
[1] TRUE
 Amina    Bao Carlos  Divya  Emeka
  TRUE  FALSE  FALSE   TRUE  FALSE
[1]  TRUE FALSE

The vector scores was created with names, so results that keep one element per score keep the names too, which makes them easy to read. tryCatch (which lesson 5 explains properly) caught the recycling warning so that you can see its message.

There are also double versions of and and or, && and ||. They work on single TRUE or FALSE values only and stop evaluating as soon as the answer is known, which is what you want in an if condition. Use & and | on vectors, && and || in if. (Since R 4.3, giving && or || a vector longer than one is an error rather than a silent use of the first element.)

Worked examplesH

Four ways to index

Square brackets select elements, and what you put inside decides how:

IndexMeaningExample
positive integersthese positionsx[c(1, 3)]
negative integersall except these positionsx[-2]
a logical vectorthe positions where it is TRUEx[x >= 60]
a character vectorthe elements with these namesx[c("Divya", "Amina")]

The logical form is the one you will use most: x[condition] is how R filters. And any of these forms can appear on the left of <- to change just those elements.

r
scores <- c(Amina = 72, Bao = 45, Carlos = 88, Divya = 59, Emeka = 91)

# Four ways to index with [ ].
scores[2]                      # by position (positions start at 1)
scores[c(1, 3, 5)]             # several positions
scores[-2]                     # negative: everything except position 2
scores[scores >= 60]           # by a logical vector: a filter
scores[c("Divya", "Amina")]    # by name

# Indexing past the end gives NA, not an error.
scores[7]

# Assigning through an index changes those elements.
scores["Bao"] <- 50
scores[scores < 60] <- scores[scores < 60] + 5     # a curve for low scores
scores

# order() returns the positions that would sort the vector.
order(scores, decreasing = TRUE)
names(scores)[order(scores, decreasing = TRUE)][1:3]   # the top three
text
Bao
 45
 Amina Carlos  Emeka
    72     88     91
 Amina Carlos  Divya  Emeka
    72     88     59     91
 Amina Carlos  Emeka
    72     88     91
Divya Amina
   59    72
<NA>
  NA
 Amina    Bao Carlos  Divya  Emeka
    72     55     88     64     91
[1] 5 3 1 4 2
[1] "Emeka"  "Carlos" "Amina"

The assignment scores[scores < 60] <- scores[scores < 60] + 5 reads naturally once you are used to it: "the scores below 60 become themselves plus 5". It changed Bao (now 50, after the earlier assignment) and Divya, and nobody else. No loop, no if.

order() deserves a moment. sort(x) returns the sorted values; order(x) returns the positions that would put x in order. Positions are more useful, because you can use them to reorder something else, such as the names, or every column of a table. The last line used them to list the three best students, highest first.

Two behaviours surprise people coming from other languages. Asking for an element past the end, scores[7], gives NA rather than an error. And mixing positive and negative indices in one bracket, such as x[c(-1, 2)], is an error, because it is unclear what you mean.

ComputationC

Sets, duplicates and counts

Many everyday questions about a vector are really questions about the set of values it contains. Which distinct values are there? Which entries repeat an earlier one? How often does each value occur? What do two vectors have in common? R answers each with one function, and because they all work on whole vectors, they combine with indexing and logical vectors in the usual way: x[!duplicated(x)] keeps first occurrences, and names(which.max(table(x))) finds the most common value.

r
# Two classes' favourite fruits, one answer per student.
class_a <- c("mango", "apple", "mango", "guava", "apple", "mango")
class_b <- c("lychee", "apple", "guava", "guava")

unique(class_a)                  # each value once, in order of first appearance
duplicated(class_a)              # TRUE where a value has been seen before
table(class_a)                   # counts per value, sorted by value

union(class_a, class_b)          # set operations treat vectors as sets
intersect(class_a, class_b)
setdiff(class_a, class_b)

# Element-wise maximum of two vectors, versus the overall maximum.
morning <- c(14, 18, 21)
evening <- c(16, 15, 22)
pmax(morning, evening)
max(morning, evening)
text
[1] "mango" "apple" "guava"
[1] FALSE FALSE  TRUE FALSE  TRUE  TRUE
class_a
apple guava mango
    2     1     3
[1] "mango"  "apple"  "guava"  "lychee"
[1] "apple" "guava"
[1] "mango"
[1] 16 18 22
[1] 22

unique() keeps values in the order they first appear, while table() sorts them, alphabetically for text; the result of table() is a named vector of counts, so everything you know about indexing works on it. union, intersect and setdiff treat their arguments as sets, discarding repeats, and return values in order of first appearance. Finally, notice the difference between pmax(), the parallel maximum, which compares the vectors element by element and returns one value per position, and max(), which returns the single largest value among all its arguments. The same pairing exists for minimums: pmin() and min(). A common use is clipping: pmin(pmax(x, 0), 100) keeps every value of x within 0 to 100.

Common misconceptionsH

Three classic pitfalls

r
# Pitfall 1: 1:length(x) when x is empty counts down from 1 to 0.
x <- c()
1:length(x)
seq_along(x)                   # the safe version: an empty sequence

# Pitfall 2: floating-point numbers are binary approximations.
0.1 + 0.2 == 0.3
isTRUE(all.equal(0.1 + 0.2, 0.3))   # compare with a tolerance
print(0.1 + 0.2, digits = 17)

# Pitfall 3: missing values spread through calculations.
heights <- c(162, NA, 175, 158)
mean(heights)
mean(heights, na.rm = TRUE)
heights > 160

# Integers and doubles: numbers are doubles unless you write L.
typeof(5); typeof(5L); typeof(1:3)
text
[1] 1 0
integer(0)
[1] FALSE
[1] TRUE
[1] 0.30000000000000004
[1] NA
[1] 165
[1]  TRUE    NA  TRUE FALSE
[1] "double"
[1] "integer"
[1] "integer"

Misconception

"for (i in 1:length(x)) loops over the elements of x." Only when x is not empty. For an empty vector, 1:length(x) is 1:0, the sequence 1, 0, so the loop runs twice with nonsense indices. Use seq_along(x) (or seq_len(n) for a count), which gives an empty sequence when there is nothing to do.

Misconception

"0.1 + 0.2 == 0.3 should be TRUE." Numbers such as 0.1 cannot be stored exactly in binary floating point, so the sum is 0.30000000000000004. This is true in every language that uses standard doubles, not a bug in R; it is famous enough to be question 7.31 of the R FAQ. Compare doubles with a tolerance: isTRUE(all.equal(a, b)).

Misconception

"A missing value is skipped automatically." In R, a calculation involving NA usually gives NA, because the true answer depends on the missing value: the mean of 162, unknown, 175 and 158 is unknown. Most summary functions take na.rm = TRUE to drop missing values first. That is a decision about your data, so make it consciously, and report how many values were missing.

The last lines show that R has two numeric types. Numbers you type are doubles (64-bit floating point) unless you add the suffix L, which makes an integer; sequences made with : are integers. In everyday analysis the difference rarely matters, because R converts as needed, but you will see both in printed output and in the next lesson.

ExplanationH

Vectorised style in practice

When experienced R programmers review code, they look for loops that could be vector operations. A loop that builds a result by appending one element at a time (result <- c(result, value)) is the classic sign of code written in another language's style: it is slow, because R copies the whole vector on every append, and it is longer than it needs to be. The vectorised form is usually a single expression: arithmetic on whole vectors, a logical index, or a function such as cumsum, pmax (element-wise maximum of several vectors) or ifelse.

Loops are not forbidden, and lesson 5 shows when they are the right tool. When you do write one, create the result vector at its full length first, with numeric(n) or character(n), and fill it by index; that avoids the repeated copying.

Two more habits are worth starting now. Give vectors meaningful names when the elements are labelled things (students, countries, months), because names survive indexing, sorting and many calculations and make output self-explanatory. And check lengths: when two vectors are meant to line up element by element, a quick stopifnot(length(a) == length(b)) catches the silent recycling that would otherwise give a plausible but wrong answer.

Exercises

Exercises

1. Vectors and vectorisation

CoreComputational

What does this print? Write it exactly as R prints it, with single spaces between the numbers.

x <- c(5, 10, 15, 20, 25, 30)
x + c(1, 100)

2. Vectors and vectorisation

CoreComputational

What number does this print?

x <- c(4, 8, 15, 16, 23, 42)
x[-c(1, 2)][2]

3. Vectors and vectorisation

CoreComputational

What does order(c(3, 9, 2, 7)) print?

4. Vectors and vectorisation

CoreComputational

Which names does this print? List them.

ages <- c(Lea = 34, Ravi = 17, Su = 25, Tom = 15, Uma = 41)
names(ages)[ages >= 18 & ages < 40]

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

5. Vectors and vectorisation

StretchComputational

This script prints two numbers. What is the second?

x <- c(2, NA, 6, 8)
sum(x > 3, na.rm = TRUE)
length(x[x > 3])

6. Vectors and vectorisation

Warm-upHuman

You want to keep the elements of temps that are below 0 or above 35. Which expression does that?

Choose one

7. Vectors and vectorisation

CoreHuman

A function loops with for (i in 1:length(x)). What happens when it is given an empty vector?

Choose one

Further reading and resources