0
0
R Programmingprogramming~20 mins

Anonymous functions in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Anonymous Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
Alist(1, 4, 9)
Bc(1, 4, 9)
Cc(1, 2, 3)
Dlist(1, 2, 3)
Attempts:
2 left
💡 Hint
Remember that lapply returns a list, not a vector.
Predict Output
intermediate
2: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)
A1 2 3 4
BNA NA NA NA
C2 4
DNA 2 NA 4
Attempts:
2 left
💡 Hint
Check how the anonymous function returns values for even and odd numbers.
🔧 Debug
advanced
2: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)
ANo error, prints list(2, 4, 6)
BNULL values in the list
CSyntaxError: unexpected end of input
DError: object 'x' not found
Attempts:
2 left
💡 Hint
Check if the function body returns a value correctly.
Predict Output
advanced
2: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)
Afunction(x) x * x
B5
C25
DError: argument is not a function
Attempts:
2 left
💡 Hint
The outer function calls the anonymous function with 5.
🧠 Conceptual
expert
3: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())
A1 2 3
B3 3 3
CError: object 'i' not found
D1 1 1
Attempts:
2 left
💡 Hint
Think about how R captures the variable i in the anonymous functions inside the loop.