Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 29 / 68

Higher-order functions (passing a function as an argument)

This lesson covers passing a function as an argument in R, with the aim of treating the work itself as a component.

Being able to pass one function into another is what makes it a higher-order function. Picture specifying only how the work should be done and leaving the doing to someone else. Passing an aggregation rule to Reduce() is the classic example.

The sample code totals a vector by passing the aggregation rule as a function, as in Reduce(function(a, b) a + b, nums). The same idea carries over to other higher-order functions such as filter and Map.

A common early stumble is simply getting used to anonymous function notation. Until function(a, b) a + b feels natural, the difference from an ordinary definition is confusing.

In professional work, it extends to designs where the logic is swapped out depending on the situation — an important part of what makes R's data handling work.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)