Inline R code in R Programming - Time & Space Complexity
We want to see how fast inline R code runs as the input size changes.
How does the time needed grow when we run code inside other code?
Analyze the time complexity of the following code snippet.
x <- 1:1000
result <- sapply(x, function(i) i * 2)
This code doubles each number in a list from 1 to 1000 using inline code inside sapply.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function doubling each number runs once per element.
- How many times: It runs exactly as many times as the length of x (1000 times here).
Each number is processed one time, so the work grows directly with the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The time grows in a straight line as input size grows.
Time Complexity: O(n)
This means the time needed grows directly in proportion to how many items we process.
[X] Wrong: "Inline code runs instantly no matter how big the input is."
[OK] Correct: Even inline code runs once per item, so more items mean more work and more time.
Understanding how inline code scales helps you explain how your code handles bigger data smoothly.
"What if we replaced sapply with a vectorized operation? How would the time complexity change?"