9  Vectors: Creation, Sequence, and Length

NoteWhat This Chapter Covers

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.

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.1 Creating a Vector with c()

NoteThe Combine Function

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.

Notec() Also Concatenates Vectors

Passing vectors to c() flattens them into a single longer vector.

WarningCoercion Inside 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()

NoteThe Constructor Form

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).

NoteTyped Shortcuts

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.

TipExpert Insight: Pre-Allocate Before Growing

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

NoteFour Ways to Make a Sequence
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.
NoteThe Colon Operator :
Noteseq() for Arbitrary Steps
Noteseq_len() and seq_along() for Safe Loops

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.

WarningCommon Mistake: 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()

NoteRepeating Values and Vectors

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).

TipExpert Insight: rep() Is How You Build Group Labels

rep() shines when building grouping variables for experiments or plots.


9.5 Length and Type

NoteAsking a Vector About Itself
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).
NoteGrowing and Shrinking with 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

NoteGiving Each Element a Label

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.

NoteRemoving and Replacing Names

9.7 Accessing Elements

NoteFour Ways to Subset a Vector
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).
WarningCommon Mistake: Indexing from 0

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

NoteAssignment Into a Subset

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

NoteBuilding and Querying a Named Vector

The whole example uses only vector features: c() to build, names() to label, numeric and logical indexing to query, and rep() to build a matching grouping vector.


9.10 Summary

NoteKey Concepts at a Glance
Concept Key Takeaway
c() The everyday way to build a vector; flattens and coerces types.
vector() and shortcuts numeric(n), integer(n), logical(n), character(n) pre-allocate.
Sequences : for integers, seq() for arbitrary steps, seq_len() and seq_along() for safe loops.
rep() Repeats values or whole vectors; each and times drive the pattern.
Length and type length(), typeof(), class(), and is.vector(); length(x) <- n resizes in place.
Names Attach labels with names() or at creation; unset with names(x) <- NULL.
Indexing Positive, negative, logical, and name-based; R is 1-indexed.
Replacement Subset on the left-hand side of <- to update in place.
TipApplying This in Practice

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.