Extracting status codes with GET()
For this last exercise, we'll switch from the read_lines()
function to the GET()
function from httr
.
We'll first create a possibly()
version of GET()
, in order to test if some of the URLs you've got return an error. If you can access the URL, a connection object will be returned. In it, you'll find a "status_code"
element.
Don't focus on the results, just remember that if a GET()
function returns an error, it's because the URL is not available. The status code number we are returning can appear a bit like web jargon, but we'll talk about it with more depth in the next chapter. Just remember, for now, that 200 means everything went as expected.
The urls
vector is available in your workspace, purrr
and httr
has been loaded for you.
This exercise is part of the course
Intermediate Functional Programming with purrr
Exercise instructions
Create a version of
GET()
that would returnNULL
in case of error.Set the names of the results.
Remove the
NULL
.Extract the
"status_code"
of each element.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
url_tester <- function(url_list){
url_list %>%
# Map a version of GET() that would otherwise return NULL
map( ___(GET, ___) ) %>%
# Set the names of the result
___( url_list ) %>%
# Remove the NULL
___() %>%
# Extract all the "status_code" elements
map(___)
}
# Try this function on the urls object
___(urls)