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, 3 returns three separate numbers; to put them into a list, you have to type [1, 2, 3]. But R is different—in R, 1, 2, 3 is 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



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:

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

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

100%
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
⚠️ Note: All elements of an R vector must be of the same type. If there are mixed types, R will automatically cast them to the "widest" type:

R
# Mixed Types:Mixing Numbers and Strings → Convert All to Strings
c(1, "a", TRUE)
# [1] "1" "a" "TRUE"
💡 Tip: This is the biggest difference between R and Python lists—R vectors are homogeneous, while Python lists are heterogeneous. To store data of different types, use a list (list()) (covered in Lesson 9).

(3) "Scalar" does not exist in R

R vectors have a hidden property: a single number is also a vector of length 1.

R
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

R
# 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()

R
# 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"
💡 Tip: The difference between 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

R
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"
⚠️ Note: This is one of the most common pitfalls in R—beginners coming from Python will instinctively write x[0], which returns an empty vector instead of the first element.

(3) Negative Integer Indexes (Excluding Elements)

R
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:

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
💡 Tip: The essence of a logical index is 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:

R
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"?

100%
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")

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

R
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
💡 Tip: This is one of R’s key advantages over Python. In Python, to add two lists, you have to use 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

R
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]
⚠️ Note: A warning will be issued if the lengths are not integer multiples of each other. This type of bug is very common in R; make sure the two vectors have the same length when writing code.

(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
💡 Tip: These aggregate functions all accept the 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()

R
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)
💡 Tip: 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

R
# ============================================
# 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))
▶ Try it Yourself

Expected Output (Excerpt):

TEXT 📖 Display only
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

Q Why do R indices start at 1 instead of 0?
A R was designed by mathematicians and follows mathematical conventions (vector elements are numbered starting from 1). This is one of the biggest differences between R and Python/Java/C. Beginners often fall into this trap: they write x[0] expecting to retrieve the first element, but end up with an empty vector numeric(0).
Q c(1, "a") What happens with this mixed-type vector?
A R automatically performs a type cast—the number 1 is converted to the string "1," resulting in the character 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.
Q Is the length of a vector fixed? Can elements be appended?
A R vectors have a fixed length (you cannot "add" or "remove" elements after creation). However, you can "reassign" them: 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.
Q What is the relationship between vectors and matrices?
A A matrix is a "two-dimensional version" of a vector—organized into rows and columns (a one-dimensional vector c(1,2,3,4,5,6) reshaped into a 2×3 matrix becomes matrix(1:6, nrow = 2)).
Q How do I choose between c() and paste()?
A 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


📝 Exercises

  1. Basic Problem: Create a vector of integers from 1 to 10 using three different methods: ① c():seq(); use identical() to verify that the results of all three are exactly the same. Take a screenshot of the console output and save it.

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

  3. Basic Exercise: Concatenate paste() with paste("Rank", 1:5, "th", sep = ""), record the result; then concatenate paste0() with paste0("x", 1:5, "y"), record the result. Take a screenshot and save it.

  4. 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; ③ Use which.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.

  5. 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 vector scores <- sample(60:100, 10) containing 10 scores; ③ Name it names(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 using sort(scores). After running the script, take a screenshot and save the entire console output.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏