01 / 20
3 7 1 9 4 [2]

Vector Indexing
in R

Learn to extract and manipulate data from R vectors using numeric, logical, and name-based indexing techniques.

R Programming

What Is a Vector?

A vector is the most fundamental data structure in R. It is an ordered collection of elements that all share the same data type: numeric, character, or logical.

10 25 37 42 58 [1] [2] [3] [4] [5]

Why Indexing Matters

Indexing lets you access, modify, and filter specific elements within a vector. Nearly every data analysis task in R relies on indexing to extract the information you need.

Extract
Pull out individual values or subsets from a dataset
Filter
Select only the elements that meet a specific condition
Modify
Change values in place without recreating the entire vector

Three Ways to Index a Vector

R provides three powerful indexing strategies. Each uses the square bracket operator \( [\;] \) but with a different type of index inside.

Numeric
Use position numbers to select by location: \( x[3] \)
Logical
Use TRUE/FALSE to filter: \( x[x > 5] \)
Name-Based
Use element names to select: \( x[\text{"age"}] \)

Numeric Indexing: The Core Rule

Place an integer (or a vector of integers) inside the brackets to select elements by their position. Negative integers exclude elements instead.

10 20 30 40 50 [1] [2] [3] [4] [5]
\( x[2] \to 20 \)
\( x[-2] \to 10, 30, 40, 50 \)

Logical Indexing: Filter by Condition

Pass a logical vector of the same length as your data vector. Elements where the condition is TRUE are kept; elements where it is FALSE are dropped.

x 3 8 2 9 5
\( x > 4 \)
FALSE TRUE FALSE TRUE TRUE result 8 9 5

Name-Based Indexing

If your vector has named elements, you can select them using a character string inside the brackets. This makes code more readable and less prone to breakage if the order changes.

# Create a named vector scores <- c("math" = 95, "english" = 88, "science" = 92) # Index by name scores["math"] # math # 95 # Multiple names scores[c("math", "science")] # math science # 95 92

Key Distinction: Single vs. Multiple

The bracket operator \( [\;] \) always returns a vector, even when selecting a single element. Compare with other languages where indexing returns a scalar.

Single Element Multiple Elements
Syntax \( x[3] \) \( x[c(1, 3, 5)] \)
Returns Vector of length 1 Vector of length \( n \)
Negative \( x[-3] \) drops 3rd \( x[-c(1,3)] \) drops 1st & 3rd
Logical Not typical \( x[x > 5] \)
Named \( x[\text{"a"}] \) \( x[c(\text{"a"},\text{"c"})] \)

Range Indexing with the Colon Operator

The colon operator \( a:b \) generates a sequence of integers from \( a \) to \( b \). This is the most common way to select a contiguous slice of a vector.

x <- c(10, 20, 30, 40, 50, 60, 70) # Select elements 2 through 5 x[2:5] # [1] 20 30 40 50 # Select the last 3 elements x[(length(x) - 2):length(x)] # [1] 50 60 70

How to Apply Vector Indexing

1
Identify your goal. Do you need a specific position, a range, or elements meeting a condition?
2
Choose the indexing type. Numeric for known positions, logical for conditions, names for labeled data.
3
Build the index vector. Use \( \text{c()} \) for multiple indices, the colon for ranges, or a comparison operator for logical masks.
4
Place inside brackets. Write \( \text{vector\_name[index]} \) and verify the result.
5
Assign to modify. Use \( x[\text{index}] \leftarrow \text{new\_value} \) to replace elements in place.

Example 1: Numeric Indexing

Given a vector of daily temperatures, extract the temperature on Wednesday (day 3) and the weekend (days 6 and 7).

temps <- c(72, 68, 75, 71, 69, 80, 82) # Wednesday temperature temps[3] # [1] 75 # Weekend temperatures temps[c(6, 7)] # [1] 80 82 # Equivalently, using the colon temps[6:7] # [1] 80 82

Example 2: Logical Filtering

From a vector of exam scores, find all scores that are above 80.

scores <- c(65, 92, 78, 85, 55, 97) # Step 1: Create logical mask scores > 80 # [1] FALSE TRUE FALSE TRUE FALSE TRUE # Step 2: Use mask to filter scores[scores > 80] # [1] 92 85 97

Example 3: Combining Techniques

Replace all negative values in a vector with 0 using logical indexing and assignment.

data <- c(5, -3, 12, -7, 8, -1) # Find negative elements data < 0 # [1] FALSE TRUE FALSE TRUE FALSE TRUE # Replace them with 0 data[data < 0] <- 0 data # [1] 5 0 12 0 8 0

The which() Function

\( \text{which()} \) converts a logical vector into numeric indices: it tells you where the TRUE values are, not what they are.

x <- c(4, 9, 1, 7, 3) # Which positions have values greater than 5? which(x > 5) # [1] 2 4 # Use the result to index x[which(x > 5)] # [1] 9 7

Common Mistakes

✕ Off-by-One
Using \( x[0] \) expecting the first element. R returns an empty vector for index 0.
✕ Mixing Signs
Writing \( x[c(1, -3)] \): R does not allow mixing positive and negative indices.
✕ Length Mismatch
Using a logical vector shorter than the data vector. R will recycle it silently, often producing wrong results.
✕ Unquoted Names
Writing \( x[\text{math}] \) instead of \( x[\text{"math"}] \). Without quotes, R looks for a variable called math.

Indexing Summary

Syntax Use Case Example
Positive Numeric \( x[i] \) Select by position \( x[3] \)
Negative Numeric \( x[-i] \) Exclude by position \( x[-2] \)
Range \( x[a:b] \) Contiguous slice \( x[2:5] \)
Logical \( x[\text{cond}] \) Filter by condition \( x[x > 5] \)
Name-Based \( x[\text{"name"}] \) Select by label \( x[\text{"age"}] \)

Question 1 of 5

Given \( x \leftarrow c(5, 12, 8, 3, 20) \), what does \( x[4] \) return?

Question 2 of 5

Given \( y \leftarrow c(10, 20, 30, 40, 50) \), what does \( y[-c(2, 4)] \) return?

Question 3 of 5

Given \( z \leftarrow c(7, 2, 9, 4, 6) \), what does \( z[z \geq 6] \) return?

Question 4 of 5

Given \( \text{info} \leftarrow c(\text{age} = 17, \text{grade} = 11, \text{gpa} = 3.8) \), which correctly returns the GPA?

Question 5 of 5

What happens when you run \( x[0] \) in R where \( x \leftarrow c(4, 8, 12) \)?