Function arguments in R Programming - Time & Space Complexity
When we use functions with arguments, it is important to see how the time to run the function changes as the input changes.
We want to know: how does the work inside the function grow when the input size grows?
Analyze the time complexity of the following code snippet.
my_sum <- function(x) {
total <- 0
for (i in seq_along(x)) {
total <- total + x[i]
}
return(total)
}
values <- 1:100
my_sum(values)
This function adds up all numbers in a vector given as an argument.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each element of the input vector.
- How many times: Once for each item in the input vector.
As the input vector gets bigger, the function does more additions, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the size of the input vector.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input vector gets bigger.
[X] Wrong: "The function runs in the same time no matter how big the input is."
[OK] Correct: Because the function adds each number one by one, more numbers mean more work and more time.
Understanding how function arguments affect time helps you explain how your code handles different input sizes clearly and confidently.
"What if the function used two loops, each going through the input vector? How would the time complexity change?"