Monday 23 March 2015

shapefile - Identify polygon containing point with R sf package


I would like to be able to map geocoded coordinates to a region on a .shp file in R using the sf package. I can load up the map and plot it but I am struggling with the code to return the region for a geocoded address.


library(sf)

library(ggplot2)

tt <- read_sf(dsn=path.expand(path), layer = "dhb2015", quiet = TRUE)
#tt <- st_transform(tt, 4326) #Not sure if this step is required with sf?
tt

Simple feature collection with 22 features and 3 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -177.3579 ymin: -47.72405 xmax: 178.8362 ymax: -33.9585

epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
# A tibble: 22 x 4
code region Shape_Leng geometry

1 01 Northland 1651929 (((174.2735 -36.28929, 174.2735 -36.28931, 174.2737 -36.28929, 174.2737 -36.28932, 1...
2 02 Waitemata 927392 (((174.5034 -37.0508, 174.5034 -37.05086, 174.5033 -37.05085, 174.5031 -37.05076, 17...
3 03 Auckland 778190 (((175.1572 -36.92584, 175.1571 -36.92585, 175.157 -36.92583, 175.1569 -36.92575, 17...
4 04 Counties Manukau 664223 (((174.9167 -36.87379, 174.9168 -36.87379, 174.9169 -36.87378, 174.9169 -36.8738, 17...
5 05 Waikato 1498296 (((175.9005 -37.22147, 175.9005 -37.22149, 175.9004 -37.22149, 175.9004 -37.22145, 1...

6 06 Lakes 623669 (((176.2863 -37.93705, 176.2879 -37.93705, 176.2881 -37.93704, 176.3047 -37.93707, 1...
7 07 Bay of Plenty 946874 (((176.1953 -37.63174, 176.1952 -37.63187, 176.1951 -37.63188, 176.1949 -37.63185, 1...
8 08 Tairawhiti 689549 (((178.0497 -38.70606, 178.0497 -38.70606, 178.0498 -38.70604, 178.0499 -38.70588, 1...
9 09 Taranaki 565796 (((174.0128 -39.06098, 174.0127 -39.06099, 174.0124 -39.06096, 174.0123 -39.06091, 1...
10 10 Hawke's Bay 945440 (((176.989 -39.85827, 176.9889 -39.85829, 176.9887 -39.85827, 176.9886 -39.85821, 17...
# ... with 12 more rows

tt %>%
ggplot() +
geom_sf(aes(fill = region))


enter image description here


I would like to be able to return the region (polygon) where a point is located.


loc=data.frame(
lon= c(175.278655),
lat= c(-37.733997),
)

I am fairly new to geographic data and would like to make use of the tidyverse and sf packages if possible.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...