Anonymous functions in R Programming - Time & Space Complexity
We want to see how the time it takes to run code with anonymous functions changes as the input grows.
How does using an anonymous function affect the work done when processing data?
Analyze the time complexity of the following code snippet.
numbers <- 1:1000
squared <- sapply(numbers, function(x) x^2)
This code squares each number in a list using an anonymous function inside sapply.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the anonymous function to each element in the list.
- How many times: Once for each number in the input list.
Each number gets processed one time, so the work grows steadily as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[X] Wrong: "Anonymous functions make the code slower because they add extra steps."
[OK] Correct: The anonymous function itself runs once per item, just like a named function would, so it doesn't add extra loops or repeated work.
Understanding how anonymous functions work with data helps you explain how your code handles tasks step-by-step, a skill useful in many coding discussions.
"What if we replaced sapply with lapply? How would the time complexity change?"