Introduction to mappers

1. Introduction to mappers

Now that you've refreshed your memory with purrr basics, it's time to dive into programming!

2. .f in purrr

Remember the basic purrr skeleton from the previous video? We've said that dot x can either be a vector, a list, or a data frame. In this course, we'll focus on the dot f part. The dot f element can be: a function, and then the function is applied to every element of dot x, a number n, then, the nth element will be extracted from each element of dot x, a character vector, where the named elements will be extracted.

3. .f as a function

In this course, we'll focus on functions, which can either be a classic function or what is called a lambda function, also known as an anonymous function. With lambda functions, we create a function "on the fly" without a name. For example, here, we create a lambda function that rounds the mean of x. Lambda functions are also called "anonymous" because we don't give them any name: they are created in the context of the iteration.

4. Mappers: part 1

With purrr, we don't need to use the full function skeleton we've seen in the previous slide. An anonymous function can be written as what is called a "mapper," which are one sided-formulas. With mappers, we use dot x to refer to the parameter of the function. You can also use a dot or dot dot one. As a convention, in this course, we'll always be using the dot x notation.

5. Mappers: part 2

If we want to use two parameters, we can use dot y to refer to the second parameter. dot dot 1 and dot dot 2 also work in this context. But what if we have more than two parameters? To do this, we can use dot dot 1, dot dot 2, dot dot 3, and so on, to refer to the first, second, third, and additional parameters.

6. as_mapper()

You can build a reusable mapper with the as_mapper() function. Mappers behave exactly like functions. The two first elements on this slide give the same result, except that the second is shorter to write and read. Creating mapper objects allows you to reuse your mapper whenever you need it and makes your code just a little bit clearer, as you can choose an explicit name for your mapper.

7. Why mappers?

Why use a mapper? For three main reasons: first, they are more concise to write. Secondly, they are easier to read than functions, as you instantly know what the operation is. And finally, thanks to the as_mapper() function, they are reusable. You have probably heard the saying that, when coding, if you have to copy and paste something more than twice, you should write a function. In purrr, if you have to use a mapper more than twice, save it with as_mapper()!

8. Let's practice!

Okay, now is the time for you to practice what we have just seen.