R: R Vectors
Last updated: 2026-08-26
In the previous lesson, we learned about the six data types in R. In this lesson, we’ll begin exploring R’s core data structure—vectors. In Python, typing
1, 2, 3returns three separate numbers; to put them into a list, you have to type[1, 2, 3]. But R is different—in R,1, 2, 3is a vector right away.
Vectors in R are the cornerstone of the entire language: numbers, strings, and boolean values are all vectors. In this lesson, we’ll delve deeply into vectors, as they’ll appear in the code for every subsequent lesson.
1. What You'll Learn
- What is an R vector, and why is it central to R?
- 4 Ways to Create Vectors (c() / : / seq() / rep())
- 5 Ways to Access Vector Elements (Positive/Negative Integers, Booleans, Names)
- Vector arithmetic (scalar + vector, vector + vector)
- 9 Common Aggregate Functions (sum, mean, sd, etc.)
- Common operations for sorting, removing duplicates, and searching
2. A Story About Student Grade Management
(1) Mission Background
Ivan is the homeroom teacher, and at the end of the semester, he needs to tally the grades of all 30 students in his class. He needs to do the following:
- Calculate the average score, the highest score, and the pass rate
- Identify students who scored 90 or higher
- Sort the scores from highest to lowest
- Assign a grade to each score (Excellent/Good/Pass/Fail)
If he used Excel, he’d have to repeatedly copy and paste + use pivot tables. If he used Python, he’d have to write lists, loops, and list comprehensions. But with R—
(2) Solution using R
# One-Line Code Generation 30 Student Grades (From 50 to 100 Random)
set.seed(42)
scores <- sample(50:100, 30, replace = TRUE)
# All statistics in a single line of code
mean(scores) # Average Score
max(scores) # Highest Score
sum(scores >= 60) / length(scores) # Pass Rate
scores[scores >= 90] # 90 Points or more
sort(scores, decreasing = TRUE) # Sort in descending order
10 lines of code to solve 5 tasks. That’s the beauty of R vectors—processing a column of data with the least amount of code.
3. What Is a Vector?
A vector is the most basic data structure in R; it is an ordered collection of elements of the same type.
(1) The Nature of Vectors
graph LR
A["R Vector"] --> B["Atomicity<br/>A single digit = Length1the vector"]
A --> C["Homogeneity<br/>All elements are of the same type"]
A --> D["Orderliness<br/>Index by Location 1-based"]
A --> E["Vectorization<br/>Operations are performed automatically on a per-element basis"]
style A fill:#fff3cd
style B fill:#cce5ff
style C fill:#d4edda
style D fill:#f8d7da
style E fill:#e1d4ff
(2) R vectors vs. Python lists
| Characteristic | R vector c(1,2,3) |
Python list [1,2,3] |
|---|---|---|
| Element Type | Must Be the Same | Can Be Different |
| Variable length | ❌ Fixed | ✅ Variable (append/remove) |
| Arithmetic Operations | Automatic Vectorization | Requires List Comprehensions |
| Index method | x[1] (1-based) |
x[0](0-based) |
| Performance | Low-level C, fast | Generic objects, slow |
# Mixed Types:Mixing Numbers and Strings → Convert All to Strings
c(1, "a", TRUE)
# [1] "1" "a" "TRUE"
(3) "Scalar" does not exist in R
R vectors have a hidden property: a single number is also a vector of length 1.
x <- 42
length(x)
# [1] 1
# That's why R All operations are, by default, "Vectorization"
c(1, 2, 3) + 10
# [1] 11 12 13
4. 4 Ways to Create Vectors
(1) Overview of Creation Methods
| Method | Syntax | Use Cases |
|---|---|---|
c() |
c(1, 2, 3) |
Manually list a few numbers (most commonly used) |
: |
1:5 |
Sequence of Consecutive Integers |
seq() |
seq(1, 10, 2) |
Arithmetic Sequence |
rep() |
rep(1:3, times = 2) |
Duplicate Elements |
| Concatenate strings |
(2) Comparison of Various Methods
# 1. c() —— concatenate(Connect),Most Commonly Used
c(10, 20, 30, 40, 50)
# [1] 10 20 30 40 50
# 2. : —— Colon Operator,Consecutive integers
1:5
# [1] 1 2 3 4 5
5:1
# [1] 5 4 3 2 1 ← Reverse Sequence
# 3. seq() —— Arithmetic Sequence
seq(from = 1, to = 10, by = 2)
# [1] 1 3 5 7 9
seq(from = 0, to = 1, length.out = 5)
# [1] 0.00 0.25 0.50 0.75 1.00
# 4. rep() —— Duplicate Elements
rep(x = 1:3, times = 2)
# [1] 1 2 3 1 2 3 ← The entire vector is repeated 2 x
rep(x = 1:3, each = 2)
# [1] 1 1 2 2 3 3 ← Repeat each element 2 x
# 5. paste() —— String Concatenation
paste("Rank", 1:3, "th")
# [1] "Rank 1 th" "Rank 2 th" "Rank 3 th"
(3) String Vectors and paste()
# paste Default sep = " "(Space)
paste("Hello", "World")
# [1] "Hello World"
# paste0 = paste(..., sep = "") No separators
paste0("Hello", "World")
# [1] "HelloWorld"
# Vectorized Concatenation
paste(c("a", "b", "c"), 1:3, sep = "-")
# [1] "a-1" "b-2" "c-3"
paste() and paste0() is that paste0() defaults to sep = "", so you type fewer characters and are 30% faster.
5. 5 Ways to Access Vector Elements
(1) Overview of Access Methods
| Method | Syntax | Meaning |
|---|---|---|
| Positive Integer Index | x[1] |
Retrieve the first element (R is 1-based) |
| Negative Integer Index | x[-1] |
Exclude the first |
| Multiple indexes | x[c(1, 3)] |
Take the 1st and 3rd |
| Logical Index | x[x > 5] |
Retrieve elements greater than 5 |
| Naming Index | x["Bob"] |
By Name |
(2) ⚠️ Important Pitfall: R is 1-based
x <- c("a", "b", "c", "d", "e")
x[1] # 1st element
# [1] "a"
x[0] # <- Error! Empty vector, no "a"
# numeric(0)
x[c(1, 3, 5)] # Multiple indexes
# [1] "a" "c" "e"
x[0], which returns an empty vector instead of the first element.
(3) Negative Integer Indexes (Excluding Elements)
x <- c("a", "b", "c", "d", "e")
x[-1] # Exclusion No. 1 ea
# [1] "b" "c" "d" "e"
x[-c(1, 3)] # Exclusion No. 1 and No. 3 ea
# [1] "b" "d" "e"
(4) Logical Index (Most Powerful)
This is the most powerful indexing method in R:
x <- c(10, 20, 30, 40, 50)
# Find the number greater than 30 the element
x[x > 30]
# [1] 40 50
# Find the even numbers
x[x %% 2 == 0]
# [1] 10 20 30 40 50
# Multiple conditions (& indicates "and", | indicates "or")
x[x > 20 & x < 50]
# [1] 30 40
x[logical vector], where positions with TRUE are retained, and positions with FALSE are filtered out.
(5) Named Indexes
Name the elements of a vector, then access them by name:
scores <- c(Alice = 85, Bob = 92, Charlie = 78)
scores
# Alice Bob Charlie
# 85 92 78
scores["Bob"]
# Bob
# 92
6. Vector Operations: Automatic Vectorization
(1) What is "vectorization"?
graph LR
A["x = 1, 2, 3"] --> C["+ 100"]
C --> D["101, 102, 103"]
E["x = 1, 2, 3"] --> F["+ y = 10, 20, 30"]
F --> G["11, 22, 33"]
style A fill:#cce5ff
style E fill:#cce5ff
style C fill:#fff3cd
style F fill:#d4edda
style D fill:#d4edda
style G fill:#d4edda
Arithmetic operations in R are "vectorized" by default—no need to write loops.
(2) Vector + Scalar (Scalar "Broadcasting")
x <- c(1, 2, 3, 4, 5)
x + 100 # 100 Broadcast to each element
# [1] 101 102 103 104 105
x * 10
# [1] 10 20 30 40 50
(3) Vector + Vector (Element-wise Operation)
x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 30, 40, 50)
x + y
# [1] 11 22 33 44 55
x * y
# [1] 10 40 90 160 250
numpy or a list comprehension, whereas in R, it can be done in a single line.
(4) It will "loop" when the lengths are different
c(1, 2, 3, 4) + c(10, 20)
# Warning: longer object length is not a multiple of shorter object length
# [1] 11 22 13 24
# The Second Vector Loop:[10, 20, 10, 20]
(5) Common Mathematical Functions (All Vectorized)
| Function | Purpose | Example |
|---|---|---|
abs() |
absolute value | abs(c(-1, -2, 3)) → 1 2 3 |
| Square root | sqrt() |
→ sqrt(c(1, 4, 9)) |
| Natural logarithm | → | |
| Rounding up | round() |
|
floor() ceiling() |
Down/Up Rounding | floor(1.6) → 1 |
7. Aggregation Functions: Collapsing Vectors into a Single Value
| Function | Purpose | Example |
|---|---|---|
sum() |
Sum | sum(1:5) → 15 |
mean() |
Average value | mean(1:5) → 3 |
median() |
Median | median(1:5) → 3 |
min() max() |
Minimum Maximum | max(1:5) → 5 |
sd() |
standard deviation | sd(1:5) → 1.581 |
var() |
variance | var(1:5) → 2.5 |
length() |
Length | length(1:5) → 5 |
prod() |
product | prod(1:5) → 120 |
na.rm = TRUE parameter to skip NA values:mean(c(1, 2, NA), na.rm = TRUE) → 1.5
8. Common Operations: Sorting, Removing Duplicates, and Searching
(1) Quick Reference Chart for the Three Major Operations
| Category | Function | Purpose |
|---|---|---|
| Sorting | sort(x) |
Sorted vector |
| Sort Order | order(x) |
Index Position after sorting |
| Sorting | rev(x) |
Reverse Vector |
| Remove Duplicates | unique(x) |
Unique Values |
| Duplicate Removal | table(x) |
Frequency Statistics |
| Set | union(a, b) |
Union |
| Set | intersect(a, b) |
Intersection |
| Set | setdiff(a, b) |
Difference set |
| Search | match("a", x) |
First occurrence |
| Search | "a" %in% x |
Does it contain the element? |
(2) Key: order() vs sort()
x <- c(3, 1, 4, 1, 5, 9, 2, 6)
# sort() Return a sorted vector
sort(x)
# [1] 1 1 2 3 4 5 6 9
# order() Return the sorted**Index**
order(x)
# [1] 2 4 7 1 3 8 6 5
# Meaning: x's 2nd element is the smallest and comes first, the 4th is the second smallest... After sorting x[order(x)] = sort(x)
order() is extremely common when sorting data frames: df[order(df$age), ] sorts by age in ascending order.
9. Complete Example: Student Grade Statistics
Below is an example of a complete workflow that ties together all the concepts covered in this lesson.
▶ Example: Comprehensive Analysis of 30 Students' Grades
# ============================================
# Comprehensive Analysis of Student Performance
# Features: Create a grade vector, do 5 Statistics by Type
# ============================================
# 1. Create 5 Student Grades(Name Vector)
scores <- c(Alice = 85, Bob = 92, Charlie = 78, David = 95, Eve = 88)
cat("Raw Scores:\n")
print(scores)
# 2. Basic Statistics
cat("\n=== Basic Statistics ===\n")
cat("Total Score:", sum(scores), "\n")
cat("Average Score:", mean(scores), "\n")
cat("Median:", median(scores), "\n")
cat("Highest Score:", max(scores), "\n")
cat("Lowest score:", min(scores), "\n")
cat("Standard Deviation:", round(sd(scores), 2), "\n")
# 3. Find the student with the highest score(Naming Index)
cat("\n=== Top-scoring student ===\n")
print(scores[scores == max(scores)])
# 4. Find 90 Points or more
cat("\n=== 90 Students scoring above a certain score ===\n")
print(scores[scores >= 90])
# 5. Identify the failing grades
cat("\n=== Students who failed(< 60)===\n")
print(scores[scores < 60])
# 6. Sort (descending)
cat("\n=== Sort by score in descending order ===\n")
print(sort(scores, decreasing = TRUE))
# 7. Standardization(z-score:Subtract the mean from all scores, then divide by the standard deviation)
z_scores <- (scores - mean(scores)) / sd(scores)
cat("\n=== Z-Score Standardization ===\n")
print(round(z_scores, 3))
# 8. Rating(Excellent/Good/Passing Grade/Fail)
ratings <- ifelse(scores >= 90, "Excellent",
ifelse(scores >= 80, "Good",
ifelse(scores >= 60, "Passing Grade", "Fail")))
cat("\n=== Rating ===\n")
print(data.frame(Fractions = scores, Rating = ratings))
Expected Output (Excerpt):
Raw Scores:
Alice Bob Charlie David Eve
85 92 78 95 88
=== Basic Statistics ===
Total Score: 438
Average Score: 87.6
Median: 88
Highest Score: 95
Lowest score: 78
Standard Deviation: 6.19
=== 90 Students scoring above a certain score ===
David
95
=== Sort by score in descending order ===
David Bob Alice Eve Charlie
95 92 85 88 78
=== Z-Score Standardization ===
Alice Bob Charlie David Eve
-0.420 0.711 -1.551 1.197 -0.097
(1) Procedure
| Step | Action | Description |
|---|---|---|
| 1 | Create RStudio Project r-vectors |
File → New Project |
| 2 | Create a new script score_analysis.R |
Copy the code above |
| 3 | Select All → Ctrl+Enter |
Send to Console |
| 4 | Observe the output | See 6 statistical results |
❓ FAQ
x[0] expecting to retrieve the first element, but end up with an empty vector numeric(0).c(1, "a") What happens with this mixed-type vector?c("1", "a"). This is R’s “type coercion” mechanism, which prevents type errors but can also hide bugs. It is recommended to always keep vectors of the same type.x <- c(x, 6) (creates a new vector and assigns x to it). Frequent appending is slow (it involves copying each time); for large datasets, use data.table or tibble.c(1,2,3,4,5,6) reshaped into a 2×3 matrix becomes matrix(1:6, nrow = 2)).c() and paste()?c() concatenates elements of any type (numbers, strings, booleans), while paste() is specifically for concatenating strings (automatically converts to characters). Use c() to construct numeric vectors, and use paste() to construct strings.📖 Summary
- A vector is the most basic data structure in R: an ordered collection of elements of the same type; there are no "scalars" in R—a single number is simply a vector of length 1.
- Creation methods:
c()for direct columns,:for integer sequences,seq()for arithmetic sequences,rep()for repetitions; usepaste()/paste0()for string concatenation - 4 indexing methods: positive integers (1-based,
x[0]is an empty vector), negative integers (exclusion), logical vectors (filtering), named indices (by name) - Arithmetic operations are automatically vectorized (vector + scalar, vector + vector), so there’s no need to write loops; common mathematical functions (sqrt, log, exp) are also processed element-by-element.
- Aggregation functions (
sum()mean()sd()median()) collapse vectors into a single value; all supportna.rm = TRUEto skip NA values - Use
sort()/order()for sorting (order returns an index),unique()for deduplication,table()for frequency,union/intersect/setdifffor sets, andmatch()/%in%for lookups
📝 Exercises
-
Basic Problem: Create a vector of integers from 1 to 10 using three different methods: ①
c()②:③seq(); useidentical()to verify that the results of all three are exactly the same. Take a screenshot of the console output and save it. -
Basic Problem: Create a vector
x <- c(2, 4, 6, 8, 10), use logical indexing to extract the elements greater than 5, and output the filtered vector. Save the code and a screenshot of the output. -
Basic Exercise: Concatenate
paste()withpaste("Rank", 1:5, "th", sep = ""), record the result; then concatenatepaste0()withpaste0("x", 1:5, "y"), record the result. Take a screenshot and save it. -
Advanced Problem: Simulate the scores of 10 students: ① Generate scores randomly using
sample(60:100, 10); ② Calculate the average, median, highest score, lowest score, and standard deviation; ③ Usewhich.max()to find the rank of the student with the highest score; ④ Count the number of students who passed (≥60). Save a screenshot of the output for each step. -
Challenge: Write a script to simulate a "student class placement" scenario: ① Create a vector
names <- c("Alice", "Bob", ...)containing the names of 10 students; ② Create a vectorscores <- sample(60:100, 10)containing 10 scores; ③ Name itnames(scores) <- names; ④ Find the names of students who scored 90 or higher; ⑤ Find the names of students who failed; ⑥ Sort them in ascending order and print them usingsort(scores). After running the script, take a screenshot and save the entire console output.