Ifelse vectorized function in R Programming - Time & Space Complexity
We want to understand how the time to run the ifelse function changes as the input grows.
Specifically, how does it handle many values quickly?
Analyze the time complexity of the following code snippet.
x <- 1:1000
result <- ifelse(x %% 2 == 0, "even", "odd")
This code checks each number in x to see if it is even or odd, then labels it accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element of the vector
xonce. - How many times: Exactly once per element, so 1000 times here.
Each element is checked one time, so the work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: If you double the input size, the work doubles too.
Time Complexity: O(n)
This means the time to run ifelse grows in a straight line with the input size.
[X] Wrong: "ifelse runs in constant time no matter how big the input is."
[OK] Correct: The function must check each element to decide what to return, so more elements mean more work.
Understanding how vectorized functions like ifelse scale helps you write efficient code and explain your choices clearly.
"What if we replaced ifelse with a loop that checks each element and appends results? How would the time complexity change?"