1 Learning Objectives

  • Create vectors using c(), seq(), and rep()
  • Perform vectorized arithmetic
  • Index and subset vectors using position, name, and logical conditions
  • Modify vector elements
  • Understand vector recycling

2 What is a Vector?

A vector is the most fundamental data structure in R: an ordered collection of values that are all the same data type. Even a single number like 5 is technically a vector of length 1.

scores <- c(88, 92, 79, 65, 100)
names_vec <- c("Aisha", "Fadumo", "Yusuf")
logical_vec <- c(TRUE, FALSE, TRUE)

scores
## [1]  88  92  79  65 100
class(scores)
## [1] "numeric"
length(scores)
## [1] 5

2.1 Other Ways to Create Vectors

seq(1, 10, by = 2)        # sequence from 1 to 10, step 2
## [1] 1 3 5 7 9
seq(0, 1, length.out = 5) # 5 evenly spaced values between 0 and 1
## [1] 0.00 0.25 0.50 0.75 1.00
1:10                       # shorthand sequence, step 1
##  [1]  1  2  3  4  5  6  7  8  9 10
rep(c("A", "B"), times = 3)  # repeat the whole vector 3 times
## [1] "A" "B" "A" "B" "A" "B"
rep(c("A", "B"), each = 3)   # repeat each element 3 times
## [1] "A" "A" "A" "B" "B" "B"

3 Vectorized Arithmetic

One of R’s most powerful features: operations apply to every element automatically — no loop needed.

heights_cm <- c(150, 160, 170, 180)
heights_m <- heights_cm / 100
heights_m
## [1] 1.5 1.6 1.7 1.8
bonus <- c(5, 10, 15, 20)
scores + bonus
## [1]  93 102  94  85 105

3.1 Vector Recycling

If two vectors have different lengths, R “recycles” (repeats) the shorter one. This is convenient but a common source of silent bugs.

c(1, 2, 3, 4) + c(10, 20)          # shorter vector recycled: 10,20,10,20
## [1] 11 22 13 24
c(1, 2, 3, 4, 5) + c(10, 20)       # length mismatch -> warning, but still runs
## Warning in c(1, 2, 3, 4, 5) + c(10, 20): longer object length is not a multiple
## of shorter object length
## [1] 11 22 13 24 15

4 Indexing (Subsetting) Vectors

R uses 1-based indexing (the first element is at position 1, not 0, unlike Python).

4.1 By Position

fruits <- c("Apple", "Banana", "Mango", "Orange", "Grapes")
fruits[1]        # first element
## [1] "Apple"
fruits[3]        # third element
## [1] "Mango"
fruits[c(1, 3)]  # first AND third
## [1] "Apple" "Mango"
fruits[-1]       # everything EXCEPT the first
## [1] "Banana" "Mango"  "Orange" "Grapes"
fruits[2:4]      # elements 2 through 4
## [1] "Banana" "Mango"  "Orange"

4.2 By Name

ages <- c(Amina = 21, Hodan = 23, Yusuf = 19)
ages["Hodan"]
## Hodan 
##    23
ages[c("Amina", "Yusuf")]
## Amina Yusuf 
##    21    19

4.3 By Logical Condition

This is one of the most powerful and commonly used features in R.

scores <- c(88, 92, 79, 65, 100, 45)
scores > 70                 # logical vector: which elements pass the test
## [1]  TRUE  TRUE  TRUE FALSE  TRUE FALSE
scores[scores > 70]         # actual values that pass the test
## [1]  88  92  79 100
scores[scores >= 50 & scores < 90]  # combine conditions
## [1] 88 79 65

5 Modifying Vector Elements

scores <- c(88, 92, 79, 65, 100)
scores[3] <- 85       # replace the 3rd element
scores
## [1]  88  92  85  65 100
scores[scores < 70] <- 70   # "curve" all failing scores up to 70
scores
## [1]  88  92  85  70 100
scores <- c(scores, 95)     # append a new value to the end
scores
## [1]  88  92  85  70 100  95

6 Useful Vector Functions

nums <- c(23, 5, 67, 12, 89, 34)

sum(nums)
## [1] 230
mean(nums)
## [1] 38.33333
max(nums)
## [1] 89
min(nums)
## [1] 5
sort(nums)               # ascending
## [1]  5 12 23 34 67 89
sort(nums, decreasing = TRUE)
## [1] 89 67 34 23 12  5
rev(nums)                # reverse order
## [1] 34 89 12 67  5 23
which(nums > 30)         # positions where condition is TRUE
## [1] 3 5 6
which.max(nums)          # position of the maximum value
## [1] 5
length(nums)
## [1] 6

7 Worked Example

Scenario: A lecturer has exam scores for 6 students and wants a quick analysis.

student_names <- c("Ali", "Sara", "Deka", "Omar", "Layla", "Hassan")
exam_scores   <- c(45, 88, 72, 91, 58, 67)

# Who passed (>= 50)?
passed_names <- student_names[exam_scores >= 50]
cat("Students who passed:", paste(passed_names, collapse = ", "), "\n")
## Students who passed: Sara, Deka, Omar, Layla, Hassan
# Class average
cat("Class average:", round(mean(exam_scores), 1), "\n")
## Class average: 70.2
# Top scorer
top_index <- which.max(exam_scores)
cat("Top scorer:", student_names[top_index], "with", exam_scores[top_index], "\n")
## Top scorer: Omar with 91

8 Practice Exercises

  1. Create a vector temperatures with 7 values (one per day of the week).
  2. Extract the temperature for the 4th day using positional indexing.
  3. Create a logical vector showing which days had a temperature above 30.
  4. Use logical indexing to extract only the days with temperature above 30.
  5. Replace the lowest temperature in the vector with 20.
  6. Use seq() to create a vector of even numbers from 2 to 20.
  7. Use rep() to create the pattern: "Mon" "Tue" "Mon" "Tue" "Mon" "Tue".
  8. Given marks <- c(56, 78, 43, 90, 61), find the positions of all marks below 60 using which().

9 Quiz: Module C

Q1. What is the index of the first element in an R vector?

  1. 0
  2. 1
  3. -1
  4. It depends on the data type

Q2. What does fruits[-2] return?

  1. Only the 2nd element
  2. Everything except the 2nd element
  3. An error
  4. The negative of the 2nd element

Q3. What happens when you add c(1,2,3,4) and c(10,20)?

  1. An error, always
  2. R recycles the shorter vector: 11, 22, 13, 24
  3. Only the first two elements are added
  4. R pads the shorter vector with zeros

Q4. Which function tells you the positions where a condition is TRUE?

  1. sum()
  2. which()
  3. sort()
  4. length()

Q5. What data structure requirement must all elements of a single vector satisfy?

  1. They must all be numbers
  2. They must all be the same data type
  3. They must all be unique
  4. There is no requirement
Click to reveal Answer Key Q1: b | Q2: b | Q3: b | Q4: b | Q5: b

10 Summary

  • Vectors are ordered, single-type collections and the building block of R.
  • Arithmetic on vectors is automatically vectorized (applied element-by-element).
  • Vectors can be indexed by position, name, or logical condition — logical indexing is especially powerful.
  • Shorter vectors are “recycled” to match longer ones during operations.