Modifying and adding elements in R Programming - Time & Space Complexity
When we change or add items in a list or vector, the time it takes can grow as the list grows.
We want to know how the work changes when the list gets bigger.
Analyze the time complexity of the following code snippet.
my_vector <- 1:5
my_vector[3] <- 10 # Modify element at position 3
my_vector <- c(my_vector, 20) # Add element at the end
This code changes one element in a vector and then adds a new element at the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Modifying an element and adding an element to a vector.
- How many times: Each operation happens once here, but adding can involve copying the whole vector.
When you change one element, it takes about the same time no matter the size.
But when you add an element, R often makes a new bigger vector and copies all old elements, so time grows with size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 copy steps when adding |
| 100 | About 100 copy steps when adding |
| 1000 | About 1000 copy steps when adding |
Pattern observation: Modifying is quick and steady; adding grows linearly with size because of copying.
Time Complexity: O(n)
This means adding an element takes time that grows in a straight line with the vector size, while modifying is fast and steady.
[X] Wrong: "Adding an element to a vector is always fast and takes the same time no matter what."
[OK] Correct: Because R often copies the whole vector to add an element, so bigger vectors take more time to add to.
Understanding how adding and changing elements affects time helps you write faster code and explain your choices clearly.
"What if we used a list instead of a vector? How would the time complexity for adding elements change?"