Purrrfecting our function
We are still perfecting our function to detect if a list of URLs contains elements that are not available.
Let's review what we have coded so far:
- An error extractor, by combining
safely()
andmap(.x, "error")
. - A "non-null" extractor, by combining
safely()
anddiscard(.x, is.null)
. - A 404 generator, by using
possibly(.x, otherwise = 404)
, which was turned into a function.
We'll change the behavior of this function a bit: you now want to be able to choose between returning either the results or the errors.
This will allow you to answer two questions with just one function: which are the unreachable URLs, and which are the reachable ones? To do this, you'll add a parameter called "type" inside this function.
The urls
vector and safe_read()
are available in your workspace.
This exercise is part of the course
Intermediate Functional Programming with purrr
Exercise instructions
Complete the function definition.
- Map
safe_read()
to the list of URLs. - Set the names of the result to the list of URLs.
- Transpose the result into a list of $result and $error.
- Use
pluck()
to extract thetype
element.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Complete the function definition
url_tester <- function(url_list, type = c("result", "error")) {
type <- match.arg(type)
url_list %>%
# Apply safe_read to each URL
___(___) %>%
# Set the names to the URLs
___(___) %>%
# Transpose into a list of $result and $error
___() %>%
# Pluck the type element
___(___)
}
# Try this function on the urls object
url_tester(urls, type = "error")