R Vectors Exercises: 12 Hands-On Problems with Step-by-Step Answers
Practice everything about R vectors: creating, indexing, filtering, modifying, vectorized operations, and handling NAs. Each exercise includes an interactive code block and a detailed solution.
These exercises progress from Easy (1-4) to Medium (5-8) to Hard (9-12). They cover the skills from the R Vectors tutorial. Try each one before checking the solution.
Easy (1-4): Creation and Access
Exercise 1: Create and Inspect
Create a numeric vector of the first 7 prime numbers. Find its length, sum, and mean.
# Exercise 1: First 7 primes
# Primes: 2, 3, 5, 7, 11, 13, 17
# Write your code below:
a <- 1:50
b <- seq(2, 30, by = 2)
c <- 100:90
d <- seq(0, 1, by = 0.1)
cat("a (1 to 50):", a, "\n\n")
cat("b (even 2-30):", b, "\n\n")
cat("c (100 to 90):", c, "\n\n")
cat("d (0.0 to 1.0):", d, "\n")
Exercise 3: Positive Indexing
Given cities <- c("Tokyo", "Delhi", "Shanghai", "Sao Paulo", "Mumbai", "Beijing", "Cairo"), extract: (a) the 3rd city, (b) the first and last city, (c) cities 2 through 5.
# Exercise 3: Access elements by position
cities <- c("Tokyo", "Delhi", "Shanghai", "Sao Paulo", "Mumbai", "Beijing", "Cairo")
# Write your code below:
Key concept: Multiplying a scalar by a named vector applies the operation to every element. Names are preserved in the result.
Exercise 8: Set Operations
Given two vectors of student IDs, find: students in both classes, students in Math only, students in Science only, and all unique students.
# Exercise 8: Student enrollment
math_students <- c(101, 103, 105, 107, 109, 111, 113)
science_students <- c(103, 106, 107, 110, 111, 114)
# 1. Students in BOTH classes
# 2. Math only (not in Science)
# 3. Science only (not in Math)
# 4. All unique students
Key concept:cumsum(), cummin(), cummax() are built-in. Running mean needs sapply() or the loop: mean of sales[1:i] for each i.
Exercise 10: Handle Missing Data
A sensor recorded temperatures but had some failures (NAs). Find the mean ignoring NAs, count the gaps, find the longest consecutive gap, and fill NAs with the last known value.
# Exercise 10: Sensor data with gaps
temps <- c(22.1, 22.3, NA, NA, 23.0, 23.2, NA, 22.8, 22.5, NA, NA, NA, 23.5, 23.1)
# 1. Mean temperature (ignoring NAs)
# 2. How many NAs? What percentage?
# 3. Fill NAs with the previous non-NA value (carry forward)
# Hint: For #3, use a loop or zoo::na.locf logic
Click to reveal solution
temps <- c(22.1, 22.3, NA, NA, 23.0, 23.2, NA, 22.8, 22.5, NA, NA, NA, 23.5, 23.1)
# 1. Mean
cat("Mean (valid):", round(mean(temps, na.rm = TRUE), 2), "\n")
# 2. NA count
na_count <- sum(is.na(temps))
cat("NAs:", na_count, "of", length(temps), "(", round(na_count/length(temps)*100, 1), "%)\n")
# 3. Fill NAs forward (carry last observation forward)
filled <- temps
for (i in 2:length(filled)) {
if (is.na(filled[i])) {
filled[i] <- filled[i - 1]
}
}
cat("\nOriginal:", temps, "\n")
cat("Filled: ", filled, "\n")
cat("Filled mean:", round(mean(filled, na.rm = TRUE), 2), "\n")
Key concept: "Last observation carried forward" (LOCF) is a common imputation method. The loop replaces each NA with the value before it. In practice, use zoo::na.locf() or tidyr::fill().
Exercise 11: Rank and Percentile
Given test scores, calculate each student's rank and percentile.
# Exercise 11: Ranking
students <- c("Alice","Bob","Carol","David","Eve","Frank","Grace","Henry")
scores <- c(88, 72, 95, 61, 88, 77, 95, 83)
# 1. Rank each student (ties get average rank)
# 2. Calculate percentile for each student
# 3. Who is in the top 25%?
# Hint: rank(), quantile()
Key concept:homework * 0.30 + midterm * 0.30 + final_exam * 0.40 computes weighted grades for ALL students at once — vectorized arithmetic across three parallel vectors.
Summary: Skills Practiced
Exercises
Vector Skills
1-4 (Easy)
c(), seq(), 1:n, positive/negative indexing
5-8 (Medium)
Logical filtering, conditional replacement, named vectors, set operations
9-12 (Hard)
cumsum(), NA handling, rank(), weighted arithmetic
What's Next?
Continue practicing with more exercise sets:
R Data Frames Exercises — 15 problems with tabular data
R Lists Exercises — 10 problems with nested structures
R Control Flow Exercises — if/else and loops practice
Or learn new concepts in the next tutorial: R Data Frames.