Bird
Raised Fist0
R Programmingprogramming~10 mins

lapply and sapply in R Programming - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - lapply and sapply
Start with a list/vector
↓
Apply function to each element
↓
lapply: returns list
↓
Output: list
Both lapply and sapply apply a function to each element of a list or vector. lapply always returns a list, while sapply tries to simplify the result to a vector or matrix if possible.
Execution Sample
R Programming
x <- list(a=1:3, b=4:6)
l1 <- lapply(x, sum)
s1 <- sapply(x, sum)
print(l1)
print(s1)
This code applies the sum function to each element of list x using lapply and sapply, then prints both results.
Execution Table
StepActionInput ElementFunction AppliedResult for ElementOutput Type
1Apply sum to x$a1, 2, 3sum6list element
2Apply sum to x$b4, 5, 6sum15list element
3lapply outputNANAlist(a=6, b=15)list
4sapply outputNANAc(a=6, b=15)named numeric vector
5EndNANAExecution completeNA
💡 All elements processed; lapply returns list, sapply returns simplified vector
Variable Tracker
VariableStartAfter Step 1After Step 2Final
xlist(a=1:3, b=4:6)list(a=1:3, b=4:6)list(a=1:3, b=4:6)list(a=1:3, b=4:6)
l1NULLlist(a=6)list(a=6, b=15)list(a=6, b=15)
s1NULLnumeric(0)numeric(0)c(a=6, b=15)
Key Moments - 3 Insights
Why does lapply always return a list even if the function returns a single number?
Because lapply is designed to keep the output structure consistent as a list, so each element's result is stored as a list element regardless of its type (see execution_table rows 3).
Why does sapply sometimes return a vector instead of a list?
sapply tries to simplify the output. If all results are single numbers, it returns a numeric vector instead of a list (see execution_table row 4).
What happens if the function returns different types or lengths for elements when using sapply?
sapply will return a list if it cannot simplify the results to a vector or matrix, preserving the original structure.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output type of lapply after processing all elements?
Anumeric vector
Blist
Cmatrix
Ddata frame
💡 Hint
Check the 'Output Type' column in execution_table row 3.
At which step does sapply produce a simplified numeric vector output?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Output Type' columns in execution_table row 4.
If the sum function returned vectors instead of single numbers, how would sapply's output change?
AIt would return a list instead of simplifying
BIt would still return a numeric vector
CIt would return NULL
DIt would cause an error
💡 Hint
Refer to key_moments about sapply simplification behavior when results differ in length or type.
Concept Snapshot
lapply(x, FUN): applies FUN to each element of x, always returns a list.
sapply(x, FUN): applies FUN and tries to simplify output to vector or matrix.
Use lapply when you want consistent list output.
Use sapply for simpler output if possible.
Both work on lists or vectors.
Full Transcript
This visual execution shows how lapply and sapply work in R. Both apply a function to each element of a list or vector. lapply always returns a list, keeping each result as a list element. sapply tries to simplify the output: if all results are single values, it returns a numeric vector instead of a list. The example applies sum to each element of a list with two numeric vectors. lapply returns a list with sums, sapply returns a named numeric vector. If the function returns different types or lengths, sapply will return a list to preserve structure. This helps beginners understand when to use each function and what output to expect.

Practice

(1/5)
1. What is the main difference between lapply and sapply in R?
easy
A. lapply modifies the original list, sapply does not.
B. lapply works only on vectors, sapply works only on lists.
C. lapply always returns a list, while sapply tries to simplify the result.
D. lapply is faster than sapply in all cases.

Solution

  1. Step 1: Understand return types of lapply and sapply

    lapply always returns a list regardless of the function applied.
  2. Step 2: Understand simplification behavior of sapply

    sapply tries to simplify the output to a vector or matrix if possible, otherwise returns a list.
  3. Final Answer:

    lapply always returns a list, while sapply tries to simplify the result. -> Option C
  4. Quick Check:

    Return type difference = lapply always returns a list, while sapply tries to simplify the result. [OK]
Hint: Remember: lapply = list output, sapply = simpler output if possible [OK]
Common Mistakes:
  • Thinking lapply works only on vectors
  • Believing sapply always returns a list
  • Assuming lapply modifies original data
2. Which of the following is the correct syntax to apply the function sqrt to each element of a list my_list using lapply?
easy
A. lapply(my_list, sqrt)
B. lapply(my_list, sqrt())
C. lapply(sqrt, my_list)
D. lapply(my_list sqrt)

Solution

  1. Step 1: Identify correct function call syntax

    The function name should be passed without parentheses to lapply, so sqrt not sqrt().
  2. Step 2: Confirm argument order

    The first argument is the list, second is the function to apply: lapply(my_list, sqrt).
  3. Final Answer:

    lapply(my_list, sqrt) -> Option A
  4. Quick Check:

    Function without () and correct order = lapply(my_list, sqrt) [OK]
Hint: Pass function name without () as second argument in lapply [OK]
Common Mistakes:
  • Using parentheses after function name inside lapply
  • Swapping argument order
  • Missing comma between arguments
3. What will be the output of the following R code?
nums <- list(a = 1:3, b = 4:6)
lapply(nums, sum)
sapply(nums, sum)
medium
A. Both return a list with sums: list(a=6, b=15)
B. lapply returns list(a=6, b=15), sapply returns numeric vector c(a=6, b=15)
C. lapply returns numeric vector, sapply returns list
D. Both return numeric vector c(6, 15)

Solution

  1. Step 1: Calculate sums for each list element

    Sum of 1:3 is 6, sum of 4:6 is 15.
  2. Step 2: Understand output types of lapply and sapply

    lapply returns a list with sums named by list elements; sapply simplifies to a numeric vector with names.
  3. Final Answer:

    lapply returns list(a=6, b=15), sapply returns numeric vector c(a=6, b=15) -> Option B
  4. Quick Check:

    lapply = list, sapply = vector if possible [OK]
Hint: lapply always list; sapply tries vector or matrix [OK]
Common Mistakes:
  • Confusing output types of lapply and sapply
  • Assuming both return same structure
  • Ignoring named elements in output
4. Consider this code snippet:
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?
medium
A. Nothing is wrong; it returns a numeric vector.
B. The anonymous function is incorrect; it should use x*x instead of x^2.
C. The list elements should be named for lapply to work.
D. Using lapply returns a list, not a numeric vector.

Solution

  1. Step 1: Understand output type of lapply

    lapply always returns a list, even if function returns single values.
  2. Step 2: Identify how to get numeric vector output

    To get a numeric vector, sapply should be used instead of lapply.
  3. Final Answer:

    Using lapply returns a list, not a numeric vector. -> Option D
  4. Quick Check:

    lapply output is list, not vector [OK]
Hint: Use sapply for vector output, lapply always returns list [OK]
Common Mistakes:
  • Thinking lapply returns vector
  • Believing function syntax is wrong
  • Assuming names are required for lapply
5. You have a list of numeric vectors: 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?
hard
A. sapply(data_list, function(x) if(length(x) == 0) NA else mean(x))
B. lapply(data_list, function(x) if(length(x) == 0) NA else mean(x))
C. sapply(data_list, mean, na.rm=TRUE)
D. lapply(data_list, mean, na.rm=TRUE)

Solution

  1. Step 1: Handle empty vectors with conditional inside function

    The function checks if length is zero, returns NA; else returns mean.
  2. Step 2: Use sapply to get numeric vector output

    Using sapply simplifies the result to a numeric vector, which is desired.
  3. Final Answer:

    sapply(data_list, function(x) if(length(x) == 0) NA else mean(x)) -> Option A
  4. Quick Check:

    Conditional function + sapply for vector output [OK]
Hint: Use sapply with if-else inside function for conditional output [OK]
Common Mistakes:
  • Using lapply and expecting vector output
  • Not handling empty vectors explicitly
  • Passing na.rm=TRUE without checking empty vectors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard