Get startedGet started for free

Building functions with compose() and negate()

1. Building functions with `compose()` and `negate()`

In this lesson, we'll go deeper into code optimization with the compose() and negate() functions.

2. compose() at will

The composition is limitless: you can build composed functions of the size you want. This means that if, for example, you have a data manipulation process that combines 20 functions, you can create a new function with compose() that will enclose all these 20 functions. Once you have this new composed element, you can run your pipeline several times, without having to copy and paste the 20 functions over and over. And again, if you need to change one thing inside this data manipulation pipeline, you just have to do it once.

3. negate()

If you need to use a negation of a predicate, for example, is.character(), is.na(), or others, you can use the negate() function. This function performs the original test, and inverts the results: TRUE becomes FALSE, and vice versa. For example, you can use this function to negate the is.na() function, and get a TRUE where the value is not missing.

4. With mappers

Of course, negate() works with mappers. Here, it might seem cumbersome to use the negate() function: why not use two mappers? The reason is simple: we are trying to make our code easier to maintain, that is to say, easier to read and change. Here, if I had chosen to use two mappers, and wanted to make a change, let's say the threshold of my mapper, I'll have to change it twice. With negate(), I only need to change it once!

5. Digression on http codes

Let's digress a minute on HTTP status codes, as we will still be working with them in the next exercises. HTTP status codes inform you about the status of the connection between your computer and a specific webpage. Status codes can go from 200 to 500. 200 and friends inform you that everything went well: these are the one we will focus on in the exercises. 300s say the connection is redirected, 400s that it failed, and 500s that there was an error on the server. If you want to know more about these codes, feel free to read the blog post linked in the slide.

6. Test if in

When doing web scraping, you might want to be sure the status code returned by a page is inside a specific range of numbers. For this, you can use the %in% operator, which tests if the element on the left is inside the element of the right. As you can see, 201 is inside the good_status vector, so our test returns TRUE.

7. Let's practice!

Let's try negate() and compose() in the exercises.