该包提供了一种处理地理特征的好方法,但我无法从需要对象的包中sf
找出一个简单的等效poly.counts
函数。GISTools
sp
poly.counts
SpatialPointsDataFrame
计算 a的多边形内 a的点数SpatialPolygonsDataFrame
,可按如下方式使用:
数据
## 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
)
计算每个多边形的点
我生成了我的两个sp
对象:
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)
现在我可以使用poly.counts
points_in_states <-
poly.counts(pts = observations_spdf, polys = sp_us_states)
将此添加到sp
对象中:
sp_us_states$points.in.state <- points_in_states
现在我已经完成了,我将转换回sf
对象并可以如下所示进行可视化:
library("leaflet")
updated_sf <- st_as_sf(sp_us_states)
updated_sf %>%
filter(points.in.state > 0) %>%
leaflet() %>%
addPolygons() %>%
addCircleMarkers(
data = observations_tibble
)
问题
我可以在没有sf
和sp
对象之间繁琐的转换的情况下执行此操作吗?