Challenge - 5 Problems
Anonymous Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of an anonymous function with lapply
What is the output of this R code using an anonymous function with
lapply?R Programming
result <- lapply(1:3, function(x) x^2) print(result)
Attempts:
2 left
💡 Hint
Remember that
lapply returns a list, not a vector.✗ Incorrect
The anonymous function squares each number from 1 to 3.
lapply returns a list of these squared values: 1, 4, and 9.❓ Predict Output
intermediate2:00remaining
Output of anonymous function with sapply
What is the output of this R code using an anonymous function with
sapply?R Programming
result <- sapply(1:4, function(x) if (x %% 2 == 0) x else NA) print(result)
Attempts:
2 left
💡 Hint
Check how the anonymous function returns values for even and odd numbers.
✗ Incorrect
The function returns the number if it is even, otherwise NA.
sapply simplifies the result to a vector: NA 2 NA 4.🔧 Debug
advanced2:00remaining
Identify the error in anonymous function usage
What error does this R code produce when run?
R Programming
result <- lapply(1:3, function(x) {x * 2 }) print(result)
Attempts:
2 left
💡 Hint
Check if the function body returns a value correctly.
✗ Incorrect
The function multiplies each number by 2 and returns it. The code runs without error and prints list(2, 4, 6).
❓ Predict Output
advanced2:00remaining
Output of nested anonymous functions
What is the output of this R code with nested anonymous functions?
R Programming
outer_func <- function(f) {
f(5)
}
result <- outer_func(function(x) x * x)
print(result)Attempts:
2 left
💡 Hint
The outer function calls the anonymous function with 5.
✗ Incorrect
The anonymous function squares its input. Called with 5, it returns 25.
🧠 Conceptual
expert3:00remaining
Understanding environment capture in anonymous functions
Consider this R code. What is the value of
result after running it?R Programming
make_funcs <- function() {
funcs <- list()
for (i in 1:3) {
funcs[[i]] <- function() i
}
funcs
}
funcs <- make_funcs()
result <- sapply(funcs, function(f) f())Attempts:
2 left
💡 Hint
Think about how R captures the variable
i in the anonymous functions inside the loop.✗ Incorrect
All functions capture the same variable
i, which after the loop ends is 3. So all return 3.