1. How to purrr safely()
In this chapter, we will cover what to do when things go wrong with lists. What if one of your elements isn't a number when you need it to be. When lists are huge finding these issues can be tough, but here, we will cover how you can take advantage of purrr functions to save you from really really big lists with issues.
2. safely()
When we try to map() over a list and one of the elements has the wrong data type, then the map() function will not work. For instance, if a function requires numeric input, and one of the elements has the character string "unknown", then the function won't work on that element.
Here we are using another purr function, safely(), inside of map() to identify where in the list an issue is occurring. Here we can see in the first part of the output, the error element contains an error message that means it can't multiply by a character string.
By using the safely() argument, otherwise, we can tell safely() how to deal with an input, such as a character string in a list of numerics, that it does not expect. Supplying NA underscore real underscore to the otherwise argument outputs an NA when an unexpected input comes from a list element, and then map() will continue on to the next element without breaking.
Using safely() along with map() produces more complex output than using map() on its own; each output list element has a result element and an error element so that you can see where the errors are occurring, and what they are. This is very useful when you go back to your original input list and determine if the element causing the error might be a data entry error or another issue that you can fix.
3. Reordering
When using safely() often our main purpose is to determine what the errors are and what elements in the list cause them. Grouping together all the error messages can help make this easier. We can do this by piping the transpose() function onto the end of our workflow. Then we can look at all the error elements together, and we can quickly see that we have an error in element 1, and not in element 2. When returning to our original data, we now know to look element 1 to diagnose our issue.
4. Let's purrr-actice!
Time to put this into practice.