Skip to content

Instantly share code, notes, and snippets.

@andrewbtran
Last active March 23, 2020 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewbtran/d0720bb1f20cd44aff8dccc2799f7f03 to your computer and use it in GitHub Desktop.
Save andrewbtran/d0720bb1f20cd44aff8dccc2799f7f03 to your computer and use it in GitHub Desktop.
covidtracking table
# This function checks if you don't have the correct packages installed yet
# If not, it will install it for you
packages <- c("tidyverse", "jsonlite", "data.table", "formattable", "scales", "knitr")
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())), repos = "http://cran.us.r-project.org")
}
# packages necessary
library(tidyverse)
library(jsonlite)
library(data.table)
library(formattable)
library(scales)
library(knitr)
# Bring in most-recent data from covidtracking.com
states <- fromJSON("https://covidtracking.com/api/states")
population_details <- read_csv("https://bit.ly/2WFbXQS")
# population from 2019 Census
# labs and reporting from reporting,
# but changes at a daily basis state by state (I am not updating this, nope, sorry)
# join the table
states_joined <- left_join(states, population_details)
# do some math, clean up the column names
states_table <- states_joined %>%
filter(!is.na(name)) %>%
mutate(Pop=paste0(round(population/1000000,1), "M")) %>%
mutate(total_per_capita=round(total/population*1000000,2),
positive_per_capita=round(positive/population*1000000,2)) %>%
ungroup() %>%
select(State=name, Pop, Labs=labs, Reporting=reporting,
`# Tested`=total,
`# Positive`=positive, `Tests per million`=total_per_capita, `Positive per million`=positive_per_capita) %>%
arrange(State)
# Create some custom colors
customGreen0 = "#DeF7E9"
customGreen = "#71CA97"
customRed = "#ff7f7f"
# Create a clean table
states_table %>%
formattable(align=c("l", "r", "l", "l", "r", "r", "r", "r"),
list(State=formatter("span", style= ~style(color="grey", font.weight="bold")),
`# Tested`=color_tile(customGreen0, customGreen),
`# Positive`=normalize_bar(customRed),
`Tests per million`=color_tile(customGreen0, customGreen),
`Positive per million`=normalize_bar(customRed)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment