Skip to content

Instantly share code, notes, and snippets.

@idshklein
Last active May 26, 2021 19:55
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 idshklein/30df513212483c6428088b265d6ab74f to your computer and use it in GitHub Desktop.
Save idshklein/30df513212483c6428088b265d6ab74f to your computer and use it in GitHub Desktop.
library(tidyverse)
library(sf)
library(spdep)
library(rnaturalearth)
names <- ne_countries() %>%
st_as_sf() %>%
st_drop_geometry() %>%
pull(name)
mat <- ne_countries() %>%
st_as_sf() %>%
poly2nb() %>%
nb2mat(zero.policy = T,style = "B")
colnames(mat) <- rownames(mat) <- names
as_tibble(mat) %>%
mutate(from = names) %>%
gather(to, connection,-from) %>%
group_by(to) %>%
summarise(n = sum(connection)) %>%
arrange(-n) %>%
left_join(ne_countries() %>%
st_as_sf(), by = c("to"= "name")) %>%
st_as_sf() %>%
mutate(n = ifelse(is.na(n),0,n)) %>%
ggplot(aes(fill = n)) +
geom_sf() +
labs(title = "Number of land borders") +
scale_fill_continuous(high = "#132B43", low = "#56B1F7")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment