R/MapCV.r

Defines functions MapCV

Documented in MapCV

#' MapCV
#' 
#' @description Map the corona virus
#' 
#' @param url_loc URL location for the data.  By default it originates from
#' the WHO website: https://covid.ourworldindata.org/data/ecdc/full_data.csv
#' @param d_start Date of first reported counts. 
#' @param d_format Date format to use for reading in d_start. 
#' 
#' @import rnaturalearth
#' @import rnaturalearthdata
#' @import ggplot2
#' @import sf
#' @import viridis
#' @import animation
#' @importFrom utils read.csv
#' 
#' @examples 
#' 
#' \dontrun{
#' # Run with defaults 
#' lastmap <- MapCV()
#' lastmap
#' }
#' 
#' 
#' \dontrun{
#' # Run specifying arguments
#' lastmap <- MapCV(url_loc = "https://covid.ourworldindata.org/data/ecdc/full_data.csv",
#' d_start = "2019-12-31", d_format = "%Y-%m-%d")
#' lastmap
#' }
#' 
#' @export
MapCV <- function(url_loc = "https://covid.ourworldindata.org/data/ecdc/full_data.csv",
                  d_start = "2019-12-31", d_format = "%Y-%m-%d"){
  
  
  #theme_set(theme_bw())
  
  #-------------------- location in WHO database         -------------------#
  world <- ne_countries(scale = 'medium', returnclass = 'sf')
  gworld <- ggplot(data = world) +
    geom_sf(aes(fill = world$region_wb))  
  
  #-------------------- Extract Data                     -------------------#
  
  corona <- read.csv(url(url_loc))
  
  
  # Fix names
  loc_levels <- levels(corona$location)
  loc_levels[loc_levels == "United States"] <- "United States of America"
  loc_levels[loc_levels == "Democratic Republic of Congo"] <- "Democratic Republic of the Congo"
  levels(corona$location) <- loc_levels
  
  m <- match(corona$location, world$geounit)
  m_na <- (1:nrow(corona))[is.na(m)]
  unique(corona$location[m_na])  # which ones missing
  corona_m <- corona[-m_na,]
  corona_m$date <- as.POSIXct(corona_m$date, format = "%Y-%m-%d", tz = "GMT")
  # ensure we have daily numbers for each country
  corona_update <- Check_Daily_Updates(corona_m)
  

  d_from <- as.POSIXct(d_start, format = d_format, tz = "GMT")
  d_to <- as.POSIXct(corona_m$date[nrow(corona_m)], format= "%Y-%m-%d", 
                     tz = "GMT")
  d_seq <- seq(from = d_from, to = d_to, by = 60*60*24)
  
  m <- list()
  for(i in 1:length(d_seq)){
    m[[i]] <- corona_map(d = d_seq[i], corona_m = corona_update, world = world)
    
  }
  
  
  gif <- function(m){
    lapply(1:length(m), function(i){ print(m[[i]])})
  }
  
  cat("Creating gif. This will take a few moments. Stand by ...\n")
  saveGIF(gif(m), interval = 1, movie.name = "corona.gif", ani.width = 1200,
          ani.height = 1200, outdir = getwd())
  
  last_map <- m[[i]]
  last_map
 
}
pkuhnert/mapcorona documentation built on March 30, 2020, 12:49 a.m.