R Console and script files in R Programming - Time & Space Complexity
When running R code in the console or script files, it's helpful to know how the time to run your code changes as your data grows.
We want to see how the time needed grows when we run commands repeatedly or on bigger inputs.
Analyze the time complexity of the following code snippet.
# Calculate squares of numbers from 1 to n
n <- 1000
result <- numeric(n)
for (i in 1:n) {
result[i] <- i^2
}
This code calculates the square of each number from 1 up to n and stores it in a 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 number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The operations increase directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of the input.
[X] Wrong: "The loop runs faster because computers are fast, so time complexity doesn't matter here."
[OK] Correct: Even if computers are fast, as n grows very large, the time will still increase linearly, so understanding this helps predict performance.
Knowing how loops in R scripts or console commands scale with input size shows you understand how your code behaves with bigger data, a key skill in programming.
"What if we replaced the for-loop with a vectorized operation like result <- (1:n)^2? How would the time complexity change?"