diff --git a/lists.Rmd b/lists.Rmd index 599140e..62f1b87 100644 --- a/lists.Rmd +++ b/lists.Rmd @@ -535,7 +535,12 @@ df %>% transpose() %>% str() When you do many operations on a list, sometimes one will fail. When this happens, you'll get an error message, and no output. This is annoying: why does one failure prevent you from accessing all the other successes? How do you ensure that one bad apple doesn't ruin the whole barrel? -In this section you'll learn how to deal this situation with a new function: `safely()`. `safely()` is an adverb: it takes a function and returns a modified function. In this case, the modified function returns a list with elements `result` (the original result) and `error` (the text of the error if it occured). For any given run, one will always be `NULL`. +In this section you'll learn how to deal this situation with a new function: `safely()`. `safely()` is an adverb: it takes a function modifies it. In this case, the modified function never throws an error and always succeeds. Instead, it returns a list with two elements: + +1. `result`: the original result. If there was an error, this will be `NULL`. + +1. `error`: the text of the error if it occured. If the operation was + successful this will be `NULL`. (You might be familiar with the `try()` function in base R. It's similar, but because it sometimes returns the original result and it sometimes returns an error object it's more difficult to work with.) @@ -572,6 +577,8 @@ x[!is_ok] y$result[is_ok] %>% flatten_dbl() ``` +(Note that you should always check that the error is null, not that the result is not-null. Sometimes the correct response is `NULL`.) + Other related functions: * `possibly()`: if you don't care about the error message, and instead @@ -770,7 +777,7 @@ Purrr comes with a number of predicate functions built-in: | `is_vector()` | x | x | x | x | x | | | `is_null()` | | | | | | x | -Compared to the base R functions, they only inspect the type of object, not its attributes. This means they tend to be less suprising: +Compared to the base R functions, they only inspect the type of the object, not its attributes. This means they tend to be less suprising: ```{r} is.atomic(NULL)