4  Vectors

Type 42 in R.

42
#> [1] 42

That [1] has been there since Chapter 1. The [1] tells you that the first value printed on this line is element 1. In R, even a single number is a vector: typing 42 creates a vector with one element.

4.1 There are no scalars

Ask R how long a number is:

length(42)
#> [1] 1
length("hello")
#> [1] 1
length(TRUE)
#> [1] 1

Each one has a length, and the length is 1. 42 is a numeric vector with one element, "hello" a character vector with one element, TRUE a logical vector with one element. Most languages keep a single number and a collection of numbers as two different kinds of thing, a scalar and an array. In R, a single number is simply a vector of length 1.

S (Section 2.3), the language R descends from, was designed for statistical computing, where you often work with whole columns of data. You might have hundreds of temperature readings and want to convert them all from Celsius to Fahrenheit. Vectors let you write that calculation once and apply it to every reading. R inherited this design: arithmetic and comparisons work element by element along a vector.

x * 2 works the same whether x has one element or a million, because x is always a vector and R needs no special case for scalars. But how do you build them?

4.2 Atomic vectors

You make a vector with c(), short for “combine”:

temperatures <- c(72, 85, 61, 90, 78)
temperatures
#> [1] 72 85 61 90 78

c() can combine vectors too:

morning <- c(58, 62, 55)
afternoon <- c(75, 80, 71)
all_temps <- c(morning, afternoon)
all_temps
#> [1] 58 62 55 75 80 71

It flattens everything into a single vector; there are no nested vectors in R, so c(c(1, 2), c(3, 4)) gives you c(1, 2, 3, 4). Look at what’s happening in c(morning, afternoon):

c(morning, afternoon)
= c(c(58, 62, 55), c(75, 80, 71))
= c(58, 62, 55, 75, 80, 71)
= [58, 62, 55, 75, 80, 71]

Each step replaces a name or function call with its value. morning becomes c(58, 62, 55), the nested c() calls flatten into one, and R creates a vector containing all six numbers.

In Section 1.2, we evaluated add(3, add(5, 10)) by replacing each function call with its result until we reached 18. The same process applies to c(morning, afternoon): the function call returns a vector containing the six values.

c(c(1, 2), c(3, 4)) and c(1, c(2, c(3, 4))) both produce c(1, 2, 3, 4); the grouping does not matter, so c() is associative. And c(x, NULL) returns x unchanged, so NULL is an identity element for it: combining with NULL does nothing. An operation that is associative and has an identity element is called a monoid. Addition with 0 is one, string concatenation with "" is one, and c() with NULL is one. The same structure is what makes Reduce() work (Chapter 21).

A few shortcuts for common patterns:

1:5
#> [1] 1 2 3 4 5
seq(0, 1, by = 0.25)
#> [1] 0.00 0.25 0.50 0.75 1.00
rep("hello", 3)
#> [1] "hello" "hello" "hello"

1:5 generates integers from 1 to 5, seq() generates a sequence with a specified step size, and rep() repeats a value.

Ask R what type each value is:

typeof(3.14)
#> [1] "double"
typeof(42L)
#> [1] "integer"
typeof("hello")
#> [1] "character"
typeof(TRUE)
#> [1] "logical"

These are the four atomic types you will use most often. double stores numbers in floating-point form, including 42 by default. To write an integer, add an L suffix: 42L. character stores text, and logical stores TRUE or FALSE. Two further types, complex and raw, are used for specialized work.

Every element in an atomic vector must have the same type. What happens if you combine values of different types?

Exercises

  1. What does c(1, c(2, c(3, 4))) produce? Predict, then check.
  2. Create a vector of the first 10 even numbers using seq().
  3. What is typeof(1)? What about typeof(1L)?

4.3 Coercion

Try mixing types in a vector:

c(1, "two", 3)
#> [1] "1"   "two" "3"

R converted the numbers to text. No warning, no error. This is called coercion, and R follows a fixed hierarchy: logical < integer < double < character. When you mix types, everything gets promoted to the most general one.

c(TRUE, 1, "hello")
#> [1] "TRUE"  "1"     "hello"

TRUE became "1" (first promoted to the integer 1, then to the string "1"), and 1 became "1".

This hierarchy explains a trick from Chapter 1 that might have seemed like magic. sum(scores > 70) works because scores > 70 produces a logical vector, and sum() coerces the logicals to numbers: TRUE becomes 1, FALSE becomes 0, so the count of passing values falls out automatically:

x <- c(65, 82, 71, 90, 55, 78)
x > 70
#> [1] FALSE  TRUE  TRUE  TRUE FALSE  TRUE
sum(x > 70)
#> [1] 4
TipOpinion

Combining types with c() can change your values without a warning. c(1, 2, "3") produces the character vector c("1", "2", "3"), so trying to add or multiply its elements gives an error. For these four types, coercion follows the order logical < integer < double < character: all elements are converted to the furthest type along that sequence.

Figure 4.1: R’s coercion hierarchy: mixing types promotes everything to the most general type.

Exercises

  1. What does TRUE + 1 return? What about FALSE * 5?
  2. What is typeof(c(1L, 1.5))? Which type won?
  3. What does as.numeric("hello") return? Read the warning.

4.4 Vectorized operations

Say you have five temperatures in Fahrenheit and want to convert them to Celsius:

temperatures <- c(72, 85, 61, 90, 78)
(temperatures - 32) * 5 / 9
#> [1] 22.22222 29.44444 16.11111 32.22222 25.55556

R subtracts 32 from each temperature, multiplies each result by 5, and divides by 9. An operation that works element by element on a vector is called a vectorized operation.

Comparisons work element by element too:

temperatures > 75
#> [1] FALSE  TRUE FALSE  TRUE  TRUE

The result is a logical vector with one value for each temperature: TRUE where the condition holds, FALSE where it doesn’t.

You can combine comparisons with & (and) and | (or). To check which temperatures are above 60 and below 85:

temperatures > 60 & temperatures < 85
#> [1]  TRUE FALSE  TRUE FALSE  TRUE

Functions such as sqrt(), log(), round(), and abs() also return one result for each input element:

sqrt(c(1, 4, 9, 16, 25))
#> [1] 1 2 3 4 5

We can describe this element-by-element calculation using the notation from Section 1.2. Let f = λx. √x, a function that takes one number and returns its square root:

c(f(1), f(4), f(9), f(16), f(25))
= c(√1, √4, √9, √16, √25)
= c(1, 2, 3, 4, 5)

Each call to f reduces to a value, and those values form the result vector. R’s sqrt() implements this calculation for a whole vector in a single call. Vectorization is a property of the function: when you write your own functions, their behavior on vectors depends on the operations you use inside them.

Even √ is not a primitive. Start with a rough guess and improve it over and over until it is close enough:

√x = iterate(λguess. (guess + x / guess) / 2, x)

Apply the refinement function λguess. (guess + x / guess) / 2 repeatedly and the result converges to √x. Square root reduces to division, addition, and repeated application of a lambda, which are themselves reducible further. At every level, the building blocks are functions applied to arguments.

In practice, R calls C’s sqrt(), which on modern CPUs maps to a hardware instruction. The chip uses a lookup table for a rough estimate, then refines it with the same (guess + x / guess) / 2 step, finishing in 10-20 clock cycles. The abstraction and the silicon converge on the same algorithm.

sqrt applied to a five-element vector returns a five-element vector; the function changes the contents, but the container keeps its shape. A structure that lets a function be mapped over it this way is called a functor. Vectors are functors, lists are functors (via lapply), and data frame columns are functors (via mutate). The word comes from category theory, but the idea is concrete: apply inside, preserve outside.

Every line of code in this chapter has run on the same substitution: names replaced by their values in c(morning, afternoon), one function replaced by five applications in sqrt(c(1, 4, 9, 16, 25)), and in both cases an expression reduced to a value.

4.4.1 Recycling

What happens when you operate on two vectors of different lengths?

c(1, 2, 3, 4) + c(10, 20)
#> [1] 11 22 13 24

R recycled the shorter vector, reusing 10, 20 to match the length of the longer one: 1+10, 2+20, 3+10, 4+20. This is also how temperatures - 32 works: 32 is a vector of length 1, and R recycles it five times to match the length of temperatures.

When the lengths don’t divide evenly, R warns you:

c(1, 2, 3, 4, 5) + c(10, 20)
#> Warning in c(1, 2, 3, 4, 5) + c(10, 20): longer object length is not a
#> multiple of shorter object length
#> [1] 11 22 13 24 15
TipOpinion

Recycling is useful when the shorter vector has length 1 (e.g., x * 2, x > 0). For anything else, match your vector lengths explicitly. A recycling warning almost always means a bug.

Exercises

  1. What does c(1, 2, 3) * c(0, 1) produce? Does R warn you?
  2. Why does x - mean(x) work without a loop? (Hint: what length is mean(x)?)
  3. What does c(TRUE, FALSE) + c(1, 2, 3, 4) produce?

4.5 Indexing

Use [ to extract elements from a vector by their position:

temperatures <- c(72, 85, 61, 90, 78)
temperatures[1]
#> [1] 72
temperatures[c(1, 3, 5)]
#> [1] 72 61 78

A negative index excludes instead:

temperatures[-2]
#> [1] 72 61 90 78

Everything except the second element. You can also index with a logical vector:

temperatures[temperatures > 75]
#> [1] 85 90 78

temperatures > 75 produces c(FALSE, TRUE, FALSE, TRUE, TRUE). Used inside [, this logical vector selects the temperatures at positions marked TRUE: 85, 90, and 78. This is called filtering. In Chapter 14, you’ll use dplyr::filter() to select rows from a data frame using conditions.

hot <- temperatures > 75
temperatures[hot]
#> [1] 85 90 78

And if the elements have names, you can index by name:

scores <- c(alice = 92, bob = 78, carol = 85)
scores["bob"]
#> bob 
#>  78
scores[c("alice", "carol")]
#> alice carol 
#>    92    85

You can also use [ to replace elements:

x <- c(10, 20, 30)
x[2] <- 99
x
#> [1] 10 99 30

The assignment updates the second element of x. If another name refers to the same vector, R copies it before making the change, so the other name retains the original values. This is copy-on-modify, introduced in Section 3.2. When R can safely modify a vector in place, it may avoid the copy. Next, we’ll look at vectors with missing values.

Exercises

  1. Extract the last element of temperatures without hard-coding the position. (Hint: length().)
  2. What does temperatures[c(TRUE, FALSE)] return? How does recycling interact with logical indexing?
  3. Create a named vector of three cities and their populations. Extract two by name.

4.6 Missing values

A sensor fails, a patient skips a visit, a field is left blank. Real data has gaps, and R represents them with NA (“Not Available”):

readings <- c(23.1, NA, 22.5, 24.0, NA, 23.8)
readings
#> [1] 23.1   NA 22.5 24.0   NA 23.8

NA is not zero, and it is not an empty string. It means “I don’t know.” And that uncertainty is contagious: any computation involving an unknown value produces an unknown result.

sum(readings)
#> [1] NA
mean(readings)
#> [1] NA

R is being honest. If you don’t know some of the values, you don’t know the sum. If you want to ignore the missing values, you have to say so explicitly:

sum(readings, na.rm = TRUE)
#> [1] 93.4
mean(readings, na.rm = TRUE)
#> [1] 23.35

na.rm = TRUE means “remove NAs before computing.” Many R functions have this argument.

Find which elements are missing with is.na():

is.na(readings)
#> [1] FALSE  TRUE FALSE FALSE  TRUE FALSE

Filter them out with ! (not):

readings[!is.na(readings)]
#> [1] 23.1 22.5 24.0 23.8

One common trap: you cannot test for NA with ==.

NA == NA
#> [1] NA

This returns NA, not TRUE. Think about it: if you don’t know what x is and you don’t know what y is, you can’t know whether they’re equal. Always use is.na().

NA represents a missing value. Adding a number to it or comparing it with another value usually returns NA, because the result depends on information you don’t have. Some operations can still give a definite answer: FALSE & NA returns FALSE, whatever the missing value might be.

In Haskell, the possibility of absence is built into the type system as Maybe. A value is either Just 42 or Nothing, and any operation on Nothing propagates Nothing forward. 1 + NA returning NA in R is the same logic as Haskell’s Nothing >>= f returning Nothing.

Rust adopted the same idea. Its equivalent of Maybe is called Option: a value is Some(42) or None, and None.map(f) returns None. The compiler rejects any code that forgets to check whether a value is present.

R’s approach is looser: nothing stops you from ignoring NA, and you will not find out until your results look wrong. The underlying rule is the same.

What happens when we apply these operations to 344 measurements, some of which are missing?

Exercises

  1. What does c(1, NA, 3) > 2 return? What happens to the NA?
  2. How many missing values are in readings? (Hint: combine sum() and is.na().)
  3. What does NA | TRUE return? What about NA & FALSE? One of each pair is not NA. Why?

4.7 Meet penguins

The penguins dataset contains measurements of penguins from the Palmer Archipelago in Antarctica. We’ll use it to apply what you’ve learned in this chapter. It is part of the datasets package, which is attached in every R session from version 4.5 on, so this chapter needs R 4.5 or later.

head(penguins)

penguins is a data frame, R’s way of storing a table. We’ll cover data frames in Chapter 11. For now, use $ to extract a column as a vector:

bill <- penguins$bill_len

Now you have a numeric vector of 344 bill length measurements, with some NAs mixed in. Everything from this chapter applies:

length(bill)
typeof(bill)
mean(bill, na.rm = TRUE)
range(bill, na.rm = TRUE)
sum(is.na(bill))
long_bills <- bill[bill > 50 & !is.na(bill)]
length(long_bills)

How many penguins have a bill longer than 50 mm? Use is.na() to identify missing measurements, logical indexing to select bills longer than 50 mm, and length() to count them. Each operation works on a vector, so you can combine them to answer a question about the measurements. In Chapter 11, we’ll work with data frames, which organize vectors of equal length into columns.

Exercises

  1. What is the mean body mass (penguins$body_mass) of the penguins? Don’t forget the NAs.
  2. How many penguins have a flipper length (penguins$flipper_len) greater than 200?
  3. What is the shortest bill in the dataset? (Hint: min() with na.rm = TRUE.)