Skip to content

Instantly share code, notes, and snippets.

@kjhealy
Last active May 27, 2020 15:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjhealy/99ed50a26441141ac5a9127838d37ccc to your computer and use it in GitHub Desktop.
Save kjhealy/99ed50a26441141ac5a9127838d37ccc to your computer and use it in GitHub Desktop.
Get Apple's COVID data in R
## 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