1. Prefilling functions
Let's take code optimization a little bit further with the partial() function.
2. Using partial()
partial() is an adverb from the purrr package that allows you to prefill the arguments of the function. In other words, it takes a function as input, then a list of named elements and the newly created function performs the original function with these elements as parameters.
Here, for example, we are creating a function that will compute the mean, but with the na.rm parameter turned to TRUE. We are also creating lm_iris(), which will compute a linear model on the iris dataset, and this dataset only.
3. Prefilling the mean() function
Again, we are doing this for the sake of clarity, maintenance, and readability. Here, with the code on the left, we would need to change our code three times to turn the na.rm argument to FALSE. We will need to do it just once with the code on the right.
A quick note: be careful to explicitly specify the name of the parameters to be filled, to allow the code to be easier to understand.
4. Using partial() and compose()
An even more powerful combination is the combination of compose() and partial().
As you can see, this code is light (not that many lines of code), easy to understand, and easy to maintain.
5. rvest
In the following exercises, we'll use several functions for web scraping with R, especially from the rvest package.
The functions you will have to call are: the read_html() function, which is used to retrieve the content of the webpage; html_nodes(), which is designed to retrieve a specific HTML node from the page; and the html_text() and html_attr() functions, which are used to get the text content and attributes from a specific node of the page.
6. Let's practice!
Now let's try some examples.