Skip to content

Instantly share code, notes, and snippets.

@k5cents
Created March 10, 2022 01:47
Show Gist options
  • Save k5cents/8dc1cff9b4275d40afb9ff56236ce1c2 to your computer and use it in GitHub Desktop.
Save k5cents/8dc1cff9b4275d40afb9ff56236ce1c2 to your computer and use it in GitHub Desktop.
Military equipment comparison
library(tidyverse)
library(janitor)
library(scales)
library(rvest)
x <- read_html("https://en.wikipedia.org/wiki/List_of_countries_by_level_of_military_equipment")
clean_wiki <- function(x) {
x %>%
str_remove_all("\\[(.*)\\]") %>%
str_remove_all("[:alpha:]") %>%
str_remove_all("/") %>%
parse_double(na = c("", "//", "TC"))
}
y <- x %>%
html_element(".wikitable") %>%
html_table() %>%
rename(`Military budget2` = 2) %>%
unite(
col = `Military budget`,
starts_with("Military budget"),
sep = ""
) %>%
rename_with(~str_remove(., "\\[(.*)\\]")) %>%
select(-Sources) %>%
mutate(across(c(`Military budget`, `Nuclear weapons`), clean_wiki)) %>%
slice_max(`Military budget`, n = 10) %>%
rename(Country = Countries) %>%
pivot_longer(
cols = -Country,
names_to = "category",
values_to = "count"
) %>%
mutate(across(count, as.integer))
y$Country[y$Country == "People's Republic of China"] <- "China"
y$Country[y$Country == "United States"] <- "USA"
y$Country[y$Country == "United Kingdom"] <- "GBR"
y$Country[y$Country == "Saudi Arabia"] <- "SAU"
y$Country[y$Country == "South Korea"] <- "Korea"
y$Country <- fct_rev(as_factor(y$Country))
y$category[y$category == "Military budget"] <- "Military budget (US$ bn)"
y$category <- as_factor(y$category)
y <- y %>%
mutate(
code = case_when(
Country == "USA" ~ "US",
Country == "China" ~ "GB",
Country == "India" ~ "IN",
Country == "GBR" ~ "GB",
Country == "France" ~ "FR",
Country == "Germany" ~ "DE",
Country == "Japan" ~ "JP",
Country == "SAU" ~ "SA",
Country == "Russia" ~ "RU",
Country == "Korea" ~ "KR"
)
)
y %>%
drop_na() %>%
ggplot(aes(x = Country, y = count)) +
geom_col(aes(fill = Country), color = "black", size = 0.25) +
geom_text(aes(label = count), hjust = -0.5) +
scale_fill_discrete(guide = "none") +
facet_wrap(~category, scales = "free_x", nrow = 2) +
scale_y_continuous(labels = label_comma(accuracy = 1)) +
coord_flip() +
labs(
title = "Military equipment of the 10 highest spending nations",
x = "",
y = ""
)
ggsave(
filename = "~/Pictures/mil_spend.png",
height = 6,
width = 12,
dpi = "retina"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment