Created
February 3, 2021 22:21
-
-
Save chrishanretty/0635b336e70e5ce68e99cf591f42fb8e to your computer and use it in GitHub Desktop.
Distances to the Storting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(sp) | |
library(raster) | |
library(viridis) | |
library(rgdal) | |
library(rnaturalearth) | |
### need two things, presumably | |
### - a polygon mask | |
### - a population raster | |
### | |
### Could in theory use a digital elevation map to get "low cost" routines not over mountains. | |
### (1) Get the polygon in to clip/extract later | |
nor_poly <- ne_countries(scale = "medium", country = "Norway") | |
### (2) Get the raster in | |
### Raster from WorldPop | |
infile <- "nor_ppp_2020_constrained.tif" | |
GDALinfo(infile) | |
nor <- raster(infile) | |
### Replace missing values with zero values | |
nor <- calc(nor, fun = function(x) { | |
replace(x, !is.finite(x), 0) | |
}) | |
### Extract the portions in the polygon | |
nor <- raster::mask(nor, nor_poly) | |
### Get the location of the Norwegian Parliament | |
### Not actually, more https://latitude.to/map/no/norway/cities/oslo | |
storting <- data.frame(x = 10.74609, y = 59.91273) | |
### Update with storting info as field value 999 | |
nor <- rasterize(storting, nor, field = 999, update=TRUE) | |
### Calculate distance to field 999, omitting areas not in polygon | |
### This might take ten minutes or so | |
d <- gridDistance(nor, origin = 999, omit=NA) | |
### We'd want to multiply the distances by the count of people and | |
### then divide by the sum of the count to get the population-weighted | |
### average distance | |
norvals <- getValues(nor) | |
d2 <- getValues(d) | |
nor_avg <- sum(norvals * d2, na.rm = TRUE) / sum(norvals, na.rm = TRUE) | |
### Would this be in metres? proj is longlat, so yes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment