Why vectors are the fundamental data structure in R Programming - Performance Analysis
We want to understand how the time it takes to work with vectors changes as the size of the vector grows.
How does the number of steps grow when we do common tasks with vectors?
Analyze the time complexity of the following code snippet.
# Create a vector of numbers from 1 to n
n <- 1000
vec <- 1:n
# Sum all elements in the vector
sum_vec <- sum(vec)
# Access the 500th element
element <- vec[500]
This code creates a vector, sums all its elements, and accesses one element by position.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing all elements requires looking at each item once.
- How many times: The sum operation goes through all n elements one by one.
When the vector size grows, the sum operation takes longer because it checks each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to sum |
| 100 | 100 steps to sum |
| 1000 | 1000 steps to sum |
Pattern observation: The time to sum grows directly with the number of elements.
Time Complexity: O(n)
This means the time to sum all elements grows in a straight line as the vector gets bigger.
[X] Wrong: "Accessing any element in a vector takes longer as the vector grows."
[OK] Correct: Accessing one element by position is very fast and does not depend on vector size.
Knowing how vector operations scale helps you write efficient R code and explain your choices clearly.
"What if we used a list instead of a vector? How would the time complexity for accessing elements change?"