7

该包提供了一种处理地理特征的好方法,但我无法从需要对象的包中sf找出一个简单的等效poly.counts函数。GISToolssp

poly.countsSpatialPointsDataFrame计算 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
  )

问题

我可以在没有sfsp对象之间繁琐的转换的情况下执行此操作吗?

4

1 回答 1

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返回这些向量的长度向量,或点数。您将看到的警告表明,尽管您有地理坐标,但底层软件假定它们是笛卡尔坐标(在这种情况下,这很可能没有问题;如果您想以正确的方式摆脱它,请移至投影坐标)

于 2017-07-26T20:43:17.850 回答