flowchart LR
A["Build"] --> C["c()"]
A --> VE["vector()"]
A --> SEQ["seq(), :, rep()"]
C --> V["A Vector"]
VE --> V
SEQ --> V
V --> I["Inspect <br> length() / names() / typeof()"]
V --> S["Subset <br> x[i] / x[name] / x[-i] / x[logical]"]
style A fill:#e3f2fd,stroke:#1976D2
style V fill:#fff3e0,stroke:#F57C00
style I fill:#e8f5e9,stroke:#388E3C
style S fill:#f3e5f5,stroke:#8E24AA
9 Vectors: Creation, Sequence, and Length
This chapter is a thorough look at the single most important data structure in R: the vector. You will learn three ways to create a vector (the c() combine function, the empty-vector constructor vector(), and sequence generators), four ways to generate sequences (:, seq(), seq_len(), seq_along()), two ways to produce repetitions (rep()), and the handful of functions that tell you a vector’s length, names, and type. You will also see how to access individual elements by position and by name, how to replace elements, and how R handles type coercion inside a single vector. By the end of this chapter you will be able to build the right kind of vector for any job and move around inside it with confidence.
9.1 Creating a Vector with c()
c() takes any number of values and combines them into a single vector. It is by far the most common way to build a vector in interactive work.
c()
Every element of a vector shares one atomic type. If you mix types inside c(), R coerces everything to the most general type in the hierarchy logical → integer → double → character.
9.2 Creating an Empty Vector with vector()
vector(mode, length) creates a vector of a given type and length, pre-filled with the type’s default “empty” value (0 for numeric, FALSE for logical, "" for character).
Each atomic type has its own shorthand: numeric(n), integer(n), logical(n), character(n), complex(n). These are the idiomatic way to pre-allocate a vector you plan to fill in a loop.
Growing a vector one element at a time with c() inside a loop is slow, R has to copy the whole vector every iteration. The idiomatic pattern is to allocate a vector of the final size up front and then fill it in.
9.3 Generating Sequences
| Tool | What It Produces | Typical Use |
|---|---|---|
a:b |
Integer sequence from a to b inclusive. |
Quick ranges: 1:10. |
seq(from, to, by) |
Arbitrary sequence with a chosen step. | Non-integer or descending steps. |
seq(from, to, length.out) |
Sequence of a given length. | Evenly spaced points on an axis. |
seq_len(n) / seq_along(x)
|
Safe integer sequences for loops. | Replaces 1:n and 1:length(x) safely. |
:
seq() for Arbitrary Steps
seq_len(n) produces 1, 2, ..., n, but when n is zero it correctly produces an empty sequence. seq_along(x) produces 1, 2, ..., length(x) with the same safety.
1:length(x) When x Is Empty
Writing 1:length(x) looks natural but misbehaves when x has zero elements: it produces c(1, 0) and iterates twice. Always prefer seq_along(x) for loops and seq_len(n) for counted sequences.
9.4 Repetitions with rep()
rep() builds a vector by repeating its input. Two arguments matter most: times (repeat the whole thing this many times) and each (repeat each element this many times).
rep() Is How You Build Group Labels
rep() shines when building grouping variables for experiments or plots.
9.5 Length and Type
| Function | Returns |
|---|---|
length(x) |
Number of elements. |
typeof(x) |
Internal storage type. |
class(x) |
User-facing class. |
is.vector(x) |
TRUE if x is a plain vector (no attributes other than names). |
length<-
Assigning to length(x) changes the size in place. Growing a vector fills the new positions with NA; shrinking truncates.
9.6 Naming Elements
Elements in a vector can have names, either given at creation time or added afterwards with names(). Named vectors are the simplest way to model a key-value lookup.
9.7 Accessing Elements
| Index Style | Example | Meaning |
|---|---|---|
| Positive integers | x[c(1, 3, 5)] |
Elements at those positions. |
| Negative integers | x[-c(1, 3)] |
All elements except those positions. |
| Logical vector | x[x > 20] |
Elements where the condition is TRUE. |
| Character names | x["banana"] |
Elements with that name (requires named vector). |
R uses 1-based indexing, not 0-based. x[0] does not return the first element; it returns an empty vector of the same type. Coming from Python, C, or Java, this tripping is almost guaranteed at least once.
9.8 Replacing Elements
Indexing on the left-hand side of <- replaces the selected elements in place. Replacement is vectorised and respects coercion.
9.9 A Worked Example: A Monthly Temperature Diary
9.10 Summary
| Concept | Description |
|---|---|
| Creation | |
| c() | Everyday constructor; flattens inputs and coerces to a common type |
| vector() and Shortcuts | numeric(n), integer(n), logical(n), character(n) pre-allocate a vector of length n |
| Sequences and Repetition | |
| Integer Sequences | a:b builds an integer sequence; seq_len(n) and seq_along(x) are safe loop helpers |
| seq() | seq(from, to, by, length.out) builds arbitrary-step sequences |
| rep() | Repeats values or whole vectors; each and times drive the pattern |
| Length, Type, and Names | |
| length() | Reports the number of elements; length(x) <- n resizes in place |
| typeof() and class() | typeof() reports the storage mode, class() the high-level class |
| is.vector() | Tests whether an object is an atomic vector without attributes beyond names |
| names() | Attach labels at creation or later; set to NULL to remove them |
| Indexing and Replacement | |
| Positive Indexing | x[1], x[c(1, 3)] picks positions directly; R indexes from 1 |
| Negative Indexing | x[-1] drops positions; combine with c() to drop several |
| Logical Indexing | x[cond] keeps elements where the logical vector is TRUE |
| Name-based Indexing | x['name'] picks by name when the vector has names attached |
| Replacement | Subset on the left-hand side of <- to update in place |
Vectors are the atoms of R. Every higher structure, list, matrix, data frame, array, is built from them. Invest the time now in building fluency with vector creation, sequences, names, and indexing; every chapter from here onward will lean on those skills. The next chapter looks at vector-level operations: sorting, ordering, the recycling rule, and how R handles missing values inside a vector.