Challenge - 5 Problems
Apply Family Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of lapply vs for loop
What is the output of the following R code snippet?
R Programming
x <- list(a = 1:3, b = 4:6) result_lapply <- lapply(x, sum) result_loop <- list() for (name in names(x)) { result_loop[[name]] <- sum(x[[name]]) } result_lapply result_loop
Attempts:
2 left
💡 Hint
Remember that lapply returns a list and for loop can build a list similarly.
✗ Incorrect
Both lapply and the for loop create lists where each element is the sum of the corresponding vector in x. So both results are identical lists with sums 6 and 15.
❓ Predict Output
intermediate2:00remaining
Output difference between sapply and for loop
What is the output of this R code?
R Programming
x <- list(a = 1:3, b = 4:6) result_sapply <- sapply(x, sum) result_loop <- numeric(length(x)) names(result_loop) <- names(x) for (i in seq_along(x)) { result_loop[i] <- sum(x[[i]]) } result_sapply result_loop
Attempts:
2 left
💡 Hint
sapply tries to simplify the result to a vector if possible.
✗ Incorrect
sapply returns a named numeric vector with sums 6 and 15. The for loop builds a numeric vector with the same values and names, so both are identical.
🧠 Conceptual
advanced1:30remaining
Why use apply family over loops?
Which of the following is the best reason to prefer apply functions over for loops in R?
Attempts:
2 left
💡 Hint
Think about code clarity and style rather than speed alone.
✗ Incorrect
Apply functions help write shorter and clearer code, improving readability. They are not always faster and do not automatically parallelize code.
❓ Predict Output
advanced1:30remaining
Output of mapply with multiple arguments
What is the output of this R code?
R Programming
x <- 1:3 y <- 4:6 result <- mapply(function(a, b) a * b, x, y) result
Attempts:
2 left
💡 Hint
mapply applies the function element-wise over multiple vectors.
✗ Incorrect
mapply multiplies corresponding elements: 1*4=4, 2*5=10, 3*6=18, returning a numeric vector.
🔧 Debug
expert2:00remaining
Identify the error in this apply usage
What error does this R code produce and why?
R Programming
mat <- matrix(1:9, nrow=3) result <- apply(mat, 2, function(x) x + y) result
Attempts:
2 left
💡 Hint
Check if all variables used inside the function are defined.
✗ Incorrect
The function uses variable y which is not defined anywhere, causing an error.