c(), seq(), and
rep()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
## [1] "numeric"
## [1] 5
## [1] 1 3 5 7 9
## [1] 0.00 0.25 0.50 0.75 1.00
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] "A" "B" "A" "B" "A" "B"
## [1] "A" "A" "A" "B" "B" "B"
One of R’s most powerful features: operations apply to every element automatically — no loop needed.
## [1] 1.5 1.6 1.7 1.8
## [1] 93 102 94 85 105
If two vectors have different lengths, R “recycles” (repeats) the shorter one. This is convenient but a common source of silent bugs.
## [1] 11 22 13 24
## 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
R uses 1-based indexing (the first element is at position 1, not 0, unlike Python).
## [1] "Apple"
## [1] "Mango"
## [1] "Apple" "Mango"
## [1] "Banana" "Mango" "Orange" "Grapes"
## [1] "Banana" "Mango" "Orange"
## Hodan
## 23
## Amina Yusuf
## 21 19
This is one of the most powerful and commonly used features in R.
## [1] TRUE TRUE TRUE FALSE TRUE FALSE
## [1] 88 92 79 100
## [1] 88 79 65
## [1] 88 92 85 65 100
## [1] 88 92 85 70 100
## [1] 88 92 85 70 100 95
## [1] 230
## [1] 38.33333
## [1] 89
## [1] 5
## [1] 5 12 23 34 67 89
## [1] 89 67 34 23 12 5
## [1] 34 89 12 67 5 23
## [1] 3 5 6
## [1] 5
## [1] 6
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: 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
temperatures with 7 values (one per day
of the week).20.seq() to create a vector of even numbers from 2 to
20.rep() to create the pattern:
"Mon" "Tue" "Mon" "Tue" "Mon" "Tue".marks <- c(56, 78, 43, 90, 61), find the
positions of all marks below 60 using which().Q1. What is the index of the first element in an R vector?
01-1Q2. What does fruits[-2] return?
Q3. What happens when you add
c(1,2,3,4) and c(10,20)?
11, 22, 13, 24Q4. Which function tells you the positions where a condition is TRUE?
sum()which()sort()length()Q5. What data structure requirement must all elements of a single vector satisfy?