Skip to main content
R Programming
CHAPTER 08 Beginner

Vectors in R

Updated: May 18, 2026
5 min read

# CHAPTER 8

Vectors in R

1. Chapter Introduction

Vectors are R's most fundamental data structure — everything in R is built on vectors. Understanding vectors deeply unlocks R's true power: vectorized computation that replaces slow loops with fast, expressive one-liners.

2. Creating Vectors

r
1234567891011121314151617181920212223
# c() — combine function (most common)
nums  <- c(10, 20, 30, 40, 50)
names_vec <- c("Alice", "Bob", "Carol", "David")
logics <- c(TRUE, FALSE, TRUE, TRUE, FALSE)

# Coercion — vectors must be same type
mixed <- c(1, 2, "three", 4)  # All become character!
class(mixed)  # "character"

# Sequence vectors
seq1 <- 1:10              # 1 2 3 4 5 6 7 8 9 10
seq2 <- seq(0, 1, 0.25)  # 0.00 0.25 0.50 0.75 1.00
seq3 <- seq(1, 100, length.out=5)  # 1 25.75 50.5 75.25 100

# Repetition
rep(0, 5)           # 0 0 0 0 0
rep(c(1,2,3), 3)    # 1 2 3 1 2 3 1 2 3
rep(c(1,2,3), each=3)  # 1 1 1 2 2 2 3 3 3

# Named vector
salary <- c(Alice=75000, Bob=62000, Carol=88000, David=55000)
salary["Alice"]  # Alice 75000
names(salary)    # "Alice" "Bob" "Carol" "David"

3. Vector Indexing

r
123456789101112131415161718192021222324
x <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

# Positive index — select elements
x[1]       # 10  (1-indexed, not 0!)
x[c(1,3,5)]  # 10 30 50
x[2:5]     # 20 30 40 50

# Negative index — EXCLUDE elements
x[-1]      # 20 30 40 50 60 70 80 90 100 (remove first)
x[-(1:3)]  # 40 50 60 70 80 90 100       (remove first 3)

# Logical index — filter by condition
x[x > 50]      # 60 70 80 90 100
x[x %% 2 == 0] # 10 20 30 40 50 60 70 80 90 100 (all even)

# Modify elements
x[1] <- 99       # Replace first element
x[x < 30] <- 0  # Set all <30 to 0

# which() — get indices of TRUE values
scores <- c(75, 92, 68, 88, 55, 79, 91)
passing_indices <- which(scores >= 70)
cat("Passing indices:", passing_indices, "\n")  # 1 2 4 6 7
cat("Passing scores: ", scores[passing_indices], "\n")

4. Vector Operations (Vectorized)

r
12345678910111213141516171819202122232425262728293031
# All operations are element-wise by default
a <- c(1, 2, 3, 4, 5)
b <- c(10, 20, 30, 40, 50)

a + b    # 11 22 33 44 55
a * b    # 10 40 90 160 250
b / a    # 10 10 10 10 10
a ^ 2    # 1 4 9 16 25

# Recycling — shorter vector is recycled
a + 100            # 101 102 103 104 105  (scalar recycled)
a + c(1, 10)       # 2 12 4 14 6  (recycled with warning for non-multiple)

# Statistical functions on vectors
scores <- c(75, 82, 91, 68, 55, 88, 79, 95, 62, 84)
sum(scores)        # 779
mean(scores)       # 77.9
median(scores)     # 81
sd(scores)         # 13.0
var(scores)        # 169.0
min(scores)        # 55
max(scores)        # 95
range(scores)      # 55 95
quantile(scores)   # 0% 25% 50% 75% 100%

# Sorting and ranking
sort(scores)          # ascending
sort(scores, decreasing=TRUE)  # descending
order(scores)         # indices that would sort the vector
rank(scores)          # rank of each element
rev(scores)           # reverse order

5. Mini Project: Student Score Analyzer

r
123456789101112131415161718192021222324252627282930313233343536373839404142434445
# ─── STUDENT SCORE ANALYZER ──────────────────────────

set.seed(42)
n <- 20
students <- paste0("Student_", sprintf("%02d", 1:n))
math    <- round(runif(n, 40, 100))
science <- round(runif(n, 40, 100))
english <- round(runif(n, 40, 100))
average <- rowMeans(cbind(math, science, english))

names(average) <- students

cat("=== STUDENT SCORE ANALYZER ===\n\n")
cat("Class Statistics:\n")
cat(sprintf("  Mean:   %.1f\n", mean(average)))
cat(sprintf("  Median: %.1f\n", median(average)))
cat(sprintf("  SD:     %.1f\n", sd(average)))
cat(sprintf("  Range:  %.0f - %.0f\n", min(average), max(average)))

# Grade distribution
grades <- cut(average, breaks=c(0,60,70,80,90,100),
               labels=c("F","D","C","B","A"), include.lowest=TRUE)
cat("\nGrade Distribution:\n")
print(table(grades))

# Top 5 performers
cat("\nTop 5 Performers:\n")
top5 <- sort(average, decreasing=TRUE)[1:5]
for (i in seq_along(top5)) {
  cat(sprintf("  %d. %-12s → %.1f\n", i, names(top5)[i], top5[i]))
}

# At-risk students (below 60)
at_risk <- students[average < 60]
if (length(at_risk) > 0) {
  cat("\nAt-Risk Students:", paste(at_risk, collapse=", "), "\n")
} else {
  cat("\nNo at-risk students!\n")
}

# Percentile ranks
pct_ranks <- round(rank(average) / length(average) * 100, 1)
names(pct_ranks) <- students
cat("\nPercentile Ranks (first 5):\n")
print(head(pct_ranks))

6. Common Mistakes

  • 1-based indexing: R uses 1-based indexing (first element is x[1], not x[0]). x[0] returns numeric(0) — an empty vector!
  • Silent vector recycling: c(1,2,3,4) + c(10,20) silently recycles to c(11,22,13,24). With non-multiples, R gives a warning but still runs — a common source of subtle bugs.

7. MCQs

Question 1

R vector indexing starts at?

Question 2

x[-c(1,3)] returns?

Question 3

which(x > 5) returns?

Question 4

rep(1:3, each=2) returns?

Question 5

Mixed types in c(1, "two", 3) result in?

Question 6

Vector recycling with non-multiple lengths?

Question 7

order(x) vs sort(x)?

Question 8

quantile(x) returns by default?

Question 9

cut(x, breaks, labels) converts numeric to?

Question 10

x[0] in R returns?

8. Interview Questions

  • Q: What is vector recycling in R and when can it cause bugs?
  • Q: What is the difference between order() and sort() in R?

9. Summary

Vectors: R's fundamental atomic data structure. Create with c(), seq(), rep(). Index with positive (select), negative (exclude), logical (filter). All operations are vectorized — x * 2 multiplies every element. Recycling: shorter vector repeats to match longer. Key functions: sort(), order(), rank(), which(), quantile(). Always use 1-based indexing.

10. Next Chapter Recommendation

In Chapter 9: Matrices and Arrays, we extend vectors to 2D matrices and multi-dimensional arrays for linear algebra and tabular computation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·