0
0
R Programmingprogramming~20 mins

lapply and sapply in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
lapply and sapply Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
Alist(a = 6, b = 15)
Blist(6, 15)
Cc(6, 15)
Dc(a = 6, b = 15)
Attempts:
2 left
💡 Hint
lapply returns a list with the same names as input.
Predict Output
intermediate
2: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)
Alist(a = 6, b = 15)
Bc(6, 15)
Cc(a = 6, b = 15)
Dmatrix(c(6, 15), nrow=1)
Attempts:
2 left
💡 Hint
sapply tries to simplify the result to a vector or matrix.
Predict Output
advanced
2: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)
A1) numeric, 2) numeric
B1) numeric, 2) list
C1) list, 2) list
D1) list, 2) numeric
Attempts:
2 left
💡 Hint
lapply always returns a list, sapply tries to simplify to vector.
🧠 Conceptual
advanced
2: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?
AA numeric matrix with 2 rows and columns equal to the number of list elements
BA list of numeric vectors
CA numeric vector with length equal to the number of list elements
DAn error because sapply cannot handle vectors
Attempts:
2 left
💡 Hint
sapply simplifies to matrix when each element returns a vector of same length.
🔧 Debug
expert
3: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?
AA list of logical vectors, one per list element
BA logical matrix with rows for each element in vectors and columns for list elements
CA logical vector with length equal to list length
DAn error because the function returns a vector
Attempts:
2 left
💡 Hint
Check how sapply simplifies when function returns vectors longer than 1.