Vector creation with c() in R Programming - Time & Space Complexity
When we create a vector using the c() function in R, it is important to understand how the time to build that vector changes as we add more elements.
We want to know how the work grows when the vector gets longer.
Analyze the time complexity of the following code snippet.
# Create a vector by combining elements
vec <- c(1, 2, 3, 4, 5)
# Add more elements
vec <- c(vec, 6, 7, 8)
# Print the vector
print(vec)
This code creates a vector by combining numbers using c(), then adds more elements by combining again.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Combining elements into a new vector using c()
- How many times: Each time c() is called, it copies all existing elements plus new ones
Each time we add elements with c(), R copies the entire vector to create a new one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 copy steps |
| 100 | About 100 copy steps |
| 1000 | About 1000 copy steps |
Pattern observation: The work grows roughly in direct proportion to the number of elements copied.
Time Complexity: O(n)
This means the time to create or extend a vector grows linearly with the number of elements.
[X] Wrong: "Adding elements with c() is always very fast no matter how many elements there are."
[OK] Correct: Each time c() is used to add elements, it copies the whole vector, so the time grows with the vector size.
Understanding how vector creation scales helps you write efficient R code and shows you can think about how programs handle data as it grows.
"What if we pre-allocate a vector of the final size and then fill it instead of using c() repeatedly? How would the time complexity change?"