Last active
May 27, 2020 15:54
-
-
Save kjhealy/99ed50a26441141ac5a9127838d37ccc to your computer and use it in GitHub Desktop.
Get Apple's COVID data in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Get current Apple COVID data | |
## Kieran Healy / @kjhealy | |
## E.g. apple_covid <- get_apple_data() | |
## 1. Find today's URL | |
## Thanks to David Cabo (@dcabo) for alerting me to the existence of the json file. | |
get_apple_target <- function(cdn_url = "https://covid19-static.cdn-apple.com", | |
json_file = "covid19-mobility-data/current/v3/index.json") { | |
tf <- tempfile(fileext = ".json") | |
curl::curl_download(paste0(cdn_url, "/", json_file), tf) | |
json_data <- jsonlite::fromJSON(tf) | |
paste0(cdn_url, json_data$basePath, json_data$regions$`en-us`$csvPath) | |
} | |
## 2. Get the data and return a tibble | |
get_apple_data <- function(url = get_apple_target(), | |
fname = "applemobilitytrends-", | |
date = stringr::str_extract(get_apple_target(), "\\d{4}-\\d{2}-\\d{2}"), | |
ext = "csv", | |
dest = "data-raw/data", | |
save_file = c("n", "y")) { | |
save_file <- match.arg(save_file) | |
message("target: ", url) | |
destination <- fs::path(here::here("data-raw/data"), | |
paste0("apple_mobility", "_daily_", date), ext = ext) | |
tf <- tempfile(fileext = ext) | |
curl::curl_download(url, tf) | |
## We don't save the file by default, but you can if you want | |
switch(save_file, | |
y = fs::file_copy(tf, destination), | |
n = NULL) | |
janitor::clean_names(readr::read_csv(tf)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment