Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in R and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic R:

nums <- list(1:3, 4:6, 7:9)
sapply(nums, sum)             # 6 15 24 — simplifies to a vector
lapply(nums, length)          # always returns a list
mapply(function(a, b) a + b, 1:3, 10:12)  # 11 13 15
# vapply is the type-safe choice (declare the result shape)
vapply(nums, max, FUN.VALUE = integer(1))

R note: The apply family is R's idiomatic higher-order toolkit, and vapply is preferred in production over sapply because it enforces the return type/length, avoiding sapply's silent shape-shifting.

Try it yourself

Exercise: In R, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in R. Mark this lesson complete and continue to the next one.