identify zip codes that fall within latitude and longitudinal coordinates

点点圈 提交于 2019-12-03 21:18:21

I use library(sf) to solve this type of point-in-polygon problem (sf is the successor to sp).

The function sf::st_intersection() gives you the intersection of two sf objects. In your case you can construct separate POLYGON and POINT sf objects.

library(sf)

Longitude <- c(-90.31914,  -90.61911,  -89.37842,  -88.0988,  -87.44875)
Latitude <- c(38.45781, 38.80097, 43.07961, 43.0624,41.49182)

## closing the polygon
Longitude[length(Longitude) + 1] <- Longitude[1]
Latitude[length(Latitude) + 1] <- Latitude[1]

## construct sf POLYGON
sf_poly <- sf::st_sf( geometry = sf::st_sfc( sf::st_polygon( x = list(matrix(c(Longitude, Latitude), ncol = 2)))) )

## construct sf POINT
sf_points <- sf::st_as_sf( cen, coords = c("Longitude2", "Latitude2"))

sf::st_intersection(sf_points, sf_poly)

# Simple feature collection with 4 features and 1 field
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -88.0228 ymin: 41.81055 xmax: -87.64957 ymax: 42.04957
# epsg (SRID):    NA
# proj4string:    NA
# CensuseZip                   geometry
# 4 SomeZipCode4 POINT (-87.64957 41.87485)
# 5 SomeZipCode5  POINT (-87.99734 42.0086)
# 6 SomeZipCode6   POINT (-87.895 42.04957)
# 7 SomeZipCode7  POINT (-88.0228 41.81055)
# Warning message:
#   attribute variables are assumed to be spatially constant throughout all geometries 

The result is all the points which are inside the polygon


You can also use sf::st_join(sf_poly, sf_points) to give the same result


And, the function sf::st_intersects(sf_points, sf_poly) will return a list saying whether the given POINT is inside the polygon

sf::st_intersects(sf_points, sf_poly)

# Sparse geometry binary predicate list of length 7, where the predicate was `intersects'
#  1: (empty)
# 2: (empty)
# 3: (empty)
# 4: 1
# 5: 1
# 6: 1
# 7: 1

Which you can use as an index / identifier of the original sf_points object to add a new column on

is_in <- sf::st_intersects(sf_points, sf_poly)

sf_points$inside_polygon <- as.logical(is_in)

sf_points
# Simple feature collection with 7 features and 2 fields
# geometry type:  POINT
# dimension:      XY
# bbox:           xmin: -133.4579 ymin: 41.81055 xmax: -87.64957 ymax: 56.37054
# epsg (SRID):    NA
# proj4string:    NA
# CensuseZip                   geometry inside_polygon
# 1 SomeZipCode1 POINT (-131.4704 55.13835)             NA
# 2 SomeZipCode2 POINT (-133.4579 56.23906)             NA
# 3 SomeZipCode3 POINT (-131.6935 56.37054)             NA
# 4 SomeZipCode4 POINT (-87.64957 41.87485)           TRUE
# 5 SomeZipCode5  POINT (-87.99734 42.0086)           TRUE
# 6 SomeZipCode6   POINT (-87.895 42.04957)           TRUE
# 7 SomeZipCode7  POINT (-88.0228 41.81055)           TRUE
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!