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

Applying a function across data with sapply()

This lesson covers applying a function across several pieces of data with R's sapply, with the aim of understanding the equivalent of map.

sapply(vector, function) performs the same work on each element of a vector and builds a new one. Picture a machine on a conveyor belt that processes every product it passes in the same way.

The sample code builds squared by squaring each element of the original vector [1, 2, 3, 4] with sapply(nums, function(x) x^2). Note the anonymous function function(x) x^2 defined on the spot.

A common early stumble is choosing between a for loop and sapply. In professional R, vectorised functions such as sapply are faster and more concise, so they are worth reaching for.

In professional work, sapply comes up constantly for applying the same calculation to every element — unit conversions, summary statistics.

๐Ÿ“– 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)