Skip to content

Instantly share code, notes, and snippets.

@chrishanretty
Created January 18, 2023 12:04
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 chrishanretty/42d551bc136c402984b83a716277a45a to your computer and use it in GitHub Desktop.
Save chrishanretty/42d551bc136c402984b83a716277a45a to your computer and use it in GitHub Desktop.
Match long/lat to local authority
### Load the necessary libraries
library(sf)
library(tidyverse)
### Read in the shapefile
### Downloaded from https://geoportal.statistics.gov.uk/datasets/ons::local-authority-districts-december-2022-boundaries-uk-bfc/explore?location=55.215430%2C-3.316939%2C6.61
lad_shp <- st_read("LAD_DEC_2022_UK_BFC.shp")
### Read in the list of coordinates
###
dat <- read.csv("Postcode data and long and lat.csv")
### Remove missing values
dat <- dat |>
subset(!is.na(Latitude)) |>
subset(!is.na(Longitude))
### Add a row number in case useful
dat$rowno <- 1:nrow(dat)
### Create this as a spatial object
### need to tell sf we're using long/lat
DT_sf = st_as_sf(dat, coords = c("Longitude", "Latitude"),
crs="+proj=longlat +datum=OSGB36")
### Make sure the coordinate systems match up
DT_sf <- st_transform(DT_sf, crs = st_crs(lad_shp))
### Map it just as a sense-check
ggplot() +
geom_sf(data = lad_shp) +
geom_sf(data = DT_sf, colour = "red") +
theme_minimal()
### Get the intersection
res <- st_intersection(DT_sf, lad_shp)
res$geometry <- NULL
res <- as.data.frame(res)
## Write out the data frame with the original columns and the LAD
write.csv(res, file = "matched_longlat.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment