Running R code in R Programming - Time & Space Complexity
When we run R code, we want to know how long it takes as the input grows.
We ask: How does the work increase when we run more or bigger data?
Analyze the time complexity of the following code snippet.
run_r_code <- function(n) {
result <- numeric(n)
for (i in 1:n) {
result[i] <- i * 2
}
return(result)
}
This code runs a loop from 1 to n and doubles each number, storing it in a result vector.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 1 to n.
- How many times: Exactly n times, once for each number.
As n grows, the loop runs more times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "The loop runs faster because doubling a number is simple."
[OK] Correct: Even if the operation is simple, the loop still runs n times, so time grows with n.
Understanding how loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the for-loop with a vectorized operation? How would the time complexity change?"