sf
包提供了一种处理地理要素的绝佳方法,但我无法找出与poly.counts
包中GISTools
函数的简单等价物。 {1}}对象。
sp
计算poly.counts
多边形中SpatialPointsDataFrame
下降的点数,可以按如下方式使用:
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
个对象之间进行繁琐的转换时执行此操作?
答案 0 :(得分: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)))
st_covers
返回一个列表,其中包含每个州所涵盖的点数索引; lengths
返回这些向量的长度向量或点数。您将看到的警告表明,虽然您有地理坐标,但基础软件假设它们是笛卡尔坐标(对于这种情况,它很可能不会有问题;如果您想要摆脱它,则移动到投影坐标正确的方式)