Challenge - 5 Problems
lapply and sapply Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of lapply with a function
What is the output of this R code?
R Programming
x <- list(a = 1:3, b = 4:6) lapply(x, sum)
Attempts:
2 left
💡 Hint
lapply returns a list with the same names as input.
✗ Incorrect
lapply applies the function to each element and returns a list preserving names.
❓ Predict Output
intermediate2:00remaining
Output of sapply with a function
What is the output of this R code?
R Programming
x <- list(a = 1:3, b = 4:6) sapply(x, sum)
Attempts:
2 left
💡 Hint
sapply tries to simplify the result to a vector or matrix.
✗ Incorrect
sapply returns a named vector when possible, here sums become a named numeric vector.
❓ Predict Output
advanced2:00remaining
Difference in output types between lapply and sapply
What is the class of the output for these two calls?
x <- list(a = 1:3, b = 4:6)
1) lapply(x, mean)
2) sapply(x, mean)
Attempts:
2 left
💡 Hint
lapply always returns a list, sapply tries to simplify to vector.
✗ Incorrect
lapply returns a list of means, sapply returns a numeric vector of means.
🧠 Conceptual
advanced2:00remaining
When does sapply return a matrix instead of a vector?
Given a list where each element is a numeric vector of length 2, what will sapply return?
Attempts:
2 left
💡 Hint
sapply simplifies to matrix when each element returns a vector of same length.
✗ Incorrect
When each element returns a vector of length > 1, sapply returns a matrix with rows = vector length.
🔧 Debug
expert3:00remaining
Why does this sapply call produce unexpected output?
Consider this code:
x <- list(a = 1:3, b = 4:6)
sapply(x, function(v) v > 2)
What is the output and why might it be confusing?
Attempts:
2 left
💡 Hint
Check how sapply simplifies when function returns vectors longer than 1.
✗ Incorrect
The function returns logical vectors of length 3, sapply simplifies to a matrix with 3 rows and 2 columns.