lapply and sapply in R Programming - Time & Space Complexity
We want to understand how the time taken by lapply and sapply grows as the input list gets bigger.
How does the number of operations change when we apply a function to many items?
Analyze the time complexity of the following code snippet.
my_list <- list(1, 2, 3, 4, 5)
result_lapply <- lapply(my_list, function(x) x * 2)
result_sapply <- sapply(my_list, function(x) x * 2)
This code applies a simple function to each item in a list using lapply and sapply.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the function to each element in the list.
- How many times: Once for each element in the list (n times).
As the list gets bigger, the function runs more times, one for each item.
| 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 number of items.
Time Complexity: O(n)
This means the time grows in a straight line as the list gets bigger.
[X] Wrong: "lapply and sapply run faster because they are special functions."
[OK] Correct: They still apply the function to each item one by one, so time grows with the number of items.
Understanding how these functions scale helps you write efficient code and explain your choices clearly in real projects.
"What if the function inside lapply took longer for bigger numbers? How would the time complexity change?"
Practice
lapply and sapply in R?Solution
Step 1: Understand return types of
lapplyandsapplylapplyalways returns a list regardless of the function applied.Step 2: Understand simplification behavior of
sapplysapplytries to simplify the output to a vector or matrix if possible, otherwise returns a list.Final Answer:
lapplyalways returns a list, whilesapplytries to simplify the result. -> Option CQuick Check:
Return type difference =lapplyalways returns a list, whilesapplytries to simplify the result. [OK]
- Thinking lapply works only on vectors
- Believing sapply always returns a list
- Assuming lapply modifies original data
sqrt to each element of a list my_list using lapply?Solution
Step 1: Identify correct function call syntax
The function name should be passed without parentheses tolapply, sosqrtnotsqrt().Step 2: Confirm argument order
The first argument is the list, second is the function to apply:lapply(my_list, sqrt).Final Answer:
lapply(my_list, sqrt) -> Option AQuick Check:
Function without () and correct order = lapply(my_list, sqrt) [OK]
- Using parentheses after function name inside lapply
- Swapping argument order
- Missing comma between arguments
nums <- list(a = 1:3, b = 4:6) lapply(nums, sum) sapply(nums, sum)
Solution
Step 1: Calculate sums for each list element
Sum of 1:3 is 6, sum of 4:6 is 15.Step 2: Understand output types of lapply and sapply
lapplyreturns a list with sums named by list elements;sapplysimplifies to a numeric vector with names.Final Answer:
lapplyreturns list(a=6, b=15),sapplyreturns numeric vector c(a=6, b=15) -> Option BQuick Check:
lapply = list, sapply = vector if possible [OK]
- Confusing output types of lapply and sapply
- Assuming both return same structure
- Ignoring named elements in output
my_list <- list(1, 2, 3) lapply(my_list, function(x) x^2)What is wrong with this code if the goal is to get a numeric vector of squared values?
Solution
Step 1: Understand output type of lapply
lapplyalways returns a list, even if function returns single values.Step 2: Identify how to get numeric vector output
To get a numeric vector,sapplyshould be used instead oflapply.Final Answer:
Usinglapplyreturns a list, not a numeric vector. -> Option DQuick Check:
lapply output is list, not vector [OK]
- Thinking lapply returns vector
- Believing function syntax is wrong
- Assuming names are required for lapply
data_list <- list(c(1,2), c(3,4,5), c(6)). You want to create a numeric vector of the means of each vector, but if a vector is empty, return NA for that element. Which code correctly does this using lapply or sapply?Solution
Step 1: Handle empty vectors with conditional inside function
The function checks if length is zero, returns NA; else returns mean.Step 2: Use sapply to get numeric vector output
Usingsapplysimplifies the result to a numeric vector, which is desired.Final Answer:
sapply(data_list, function(x) if(length(x) == 0) NA else mean(x)) -> Option AQuick Check:
Conditional function + sapply for vector output [OK]
- Using lapply and expecting vector output
- Not handling empty vectors explicitly
- Passing na.rm=TRUE without checking empty vectors
Ready to prove it?
Pass the test and this pattern moves unknown
