Lesson 4 / 25

Vectors, Recycling and Indexing

Create and index vectors, and understand recycling and vectorised operations.

Everything is a vector

An atomic vector holds elements of one type, created with c(), sequences (1:10, seq(0, 1, by = 0.25)) or rep(). If you combine types, R coerces to the most flexible one: c(1, "a") becomes character. Operations are vectorised: prices * 1.18 multiplies every element. When two vectors of different lengths meet, R recycles the shorter one; this is convenient for scalars but can hide bugs, and R warns only when the longer length is not a multiple of the shorter. Indexing starts at 1. Index with positive integers (x[c(1, 3)]), negative integers to exclude (x[-1] drops the first element, it does not count from the end), logical vectors (x[x > 50]), or names (x["Pune"]) for named vectors. Useful functions: length, sum, mean, max, which, which.max, cumsum, rev, sort, order, unique, table, %in% and ifelse for vectorised conditionals.

Vectorised operations

An operation applies element by element across a whole vector, recycling a shorter operand.

Two rows of boxes aligned vertically with arrows between each pair, producing a third row of result boxes.
Figure 2.1 — Element-wise operations and recycling.

Vector operations and indexing

Logical indexing and named vectors are everyday R tools.

prices <- c(pen = 49.5, notebook = 120, ink = 199, eraser = 15)

prices * 1.18                       # GST on every item
prices["ink"]                       # by name
prices[c(1, 3)]                     # by position (1-based)
prices[-1]                          # everything except the first
prices[prices > 100]                # logical indexing

names(which.max(prices))            # "ink"
sort(prices, decreasing = TRUE)

category <- ifelse(prices >= 100, "premium", "basic")   # vectorised if
table(category)                     # counts per category

"ink" %in% names(prices)            # TRUE

c(1, 2, 3, 4) + c(10, 20)           # recycling: 11 22 13 24
c(1, 2, 3) + c(10, 20)              # works, but with a warning (3 is not a multiple of 2)

Negative indices exclude

In Python, x[-1] is the last element. In R, x[-1] removes the first element. Use x[length(x)] or tail(x, 1) for the last element.

Quick check: In R, what does x[-2] return for x <- c(10, 20, 30)?

  • 20
  • 30
  • c(10, 30)
  • An error
Answer

c(10, 30) — Negative indices exclude elements, so the second element is dropped.