R Markdown document creation in R Programming - Time & Space Complexity
When creating an R Markdown document, it's helpful to understand how the time to generate the document grows as you add more content or code chunks.
We want to know how the processing time changes as the document size increases.
Analyze the time complexity of the following R code chunk inside an R Markdown document.
for (i in 1:n) {
print(i)
Sys.sleep(0.1) # simulate some processing time
}
This code prints numbers from 1 to n, simulating work in each step.
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 print and sleep operations grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print and sleep steps |
| 100 | 100 print and sleep steps |
| 1000 | 1000 print and sleep steps |
Pattern observation: Doubling n doubles the work; the growth is steady and direct.
Time Complexity: O(n)
This means the time to create the document grows directly in proportion to the number of code chunks or lines processed.
[X] Wrong: "Adding more lines won't affect the time much because computers are fast."
[OK] Correct: Even though computers are fast, each line or chunk adds work. More lines mean more steps, so time grows with size.
Understanding how document size affects processing time helps you write efficient reports and shows you can think about performance in real tasks.
"What if we replaced the for-loop with a vectorized print statement? How would the time complexity change?"