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

Transforming a vector with sapply (the map equivalent)

This lesson covers transforming a vector with R's sapply, with the aim of understanding the equivalent of map.

sapply(vector, function) performs the same work on each element and builds a new vector. It corresponds to the map function of other languages and is R's basic vector-transformation mechanism.

The sample code builds doubled by doubling each element of the original vector [1, 2, 3] with sapply(nums, function(n) n * 2). Note the anonymous function function(n) n * 2 defined on the spot.

A common early stumble is not realising this same work can be done with plain vector arithmetic: nums * 2. R often lets you apply an operation directly to a vector without sapply at all.

In professional work, the usual split is vector arithmetic for simple calculations and sapply for anything more involved.

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