Equivalent of `poly.counts` to count lat/long pairs falling inside of polygons with the sf package
数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ## Libraries library("GISTools") library("tidyverse") library("sf") library("sp") library("rgdal") ## Obtain shapefiles download.file(url ="https://www2.census.gov/geo/tiger/TIGER2016/STATE/tl_2016_us_state.zip", destfile ="data-raw/states.zip") unzip(zipfile ="data-raw/states.zip", exdir ="data-raw/states") sf_us_states <- read_sf("data-raw/states") ## Our observations: observations_tibble <- tribble( ~lat, ~long, 31.968599, -99.901813, 35.263266, -80.854385, 35.149534, -90.04898, 41.897547, -84.037166, 34.596759, -86.965563, 42.652579, -73.756232, 43.670406, -93.575858 ) |
计算每个多边形的点
我生成了两个
1 2 3 4 5 6 7 | sp_us_states <- as(sf_us_states,"Spatial") observations_spdf <- observations_tibble %>% select(long, lat) %>% # SPDF want long, lat pairs SpatialPointsDataFrame(coords = ., data = ., proj4string = sp_us_states@proj4string) |
现在我可以使用
1 2 | points_in_states <- poly.counts(pts = observations_spdf, polys = sp_us_states) |
将此添加到
1 | sp_us_states$points.in.state <- points_in_states |
现在我已经完成了,我将转换回
1 2 3 4 5 6 7 8 9 | library("leaflet") updated_sf <- st_as_sf(sp_us_states) updated_sf %>% filter(points.in.state > 0) %>% leaflet() %>% addPolygons() %>% addCircleMarkers( data = observations_tibble ) |
问题
我可以在不进行
尝试以下方法:
1 2 3 4 5 | sf_obs = st_as_sf(observations_tibble, coords = c("long","lat"), crs = st_crs(sf_us_states)) lengths(st_covers(sf_us_states, sf_obs)) # check: summary(points_in_states - lengths(st_covers(sf_us_states, sf_obs))) |