使用sf,选择包含至少一种点要素的区域要素?

时间:2019-03-21 07:53:53

标签: r sf

例如,假设我有一个new java.text.SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss").format(new Date())对象,其中包含美国连续4个城市及其坐标。然后,我有一个具有48个功能的createHeader对象(每个可能的状态一个)。有没有办法选择包含指定城市的州的子集?像这样:

sf

编辑sf给了我

cities_sf

state_sf %>%
  filter(states s.t. there exists x in cities_sf s.t. x in states_sf) +
  ggplot() +
  ...

我可以说这26个索引对应于st_within(my_cities, my_states)中包含城市的多面体,但是我不确定如何使用该SGBD(根据文档,“稀疏几何二进制谓词”) structure(list(290L, 378L, 51L, integer(0), 283L, 478L, 415L, 380L, 489L, 64L, 189L, 184L, 311L, 488L, 66L, 73L, 49L, 1L, 359L, 111L, 502L, 489L, 272L, 115L, 352L, 241L), predicate = "within", region.id = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26"), ncol = 544L, class = "sgbp") / my_states中的对象

编辑2 :我最终使用了ggplot,它提供了一个geom_sf对象,这是我需要的子集

2 个答案:

答案 0 :(得分:3)

使用USAboundaries包中的us_states函数,可以使状态变少:

> states <- us_states(map_date = "2000-01-01", resolution = "high", states = c("CA", "OR", "WA","NV","NM","UT","CO","ID","AZ"))

这是我创建的一些要点:

> pts
Simple feature collection with 4 features and 0 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: -121.7663 ymin: 34.86508 xmax: -110.7263 ymax: 46.65593
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
                    geometry
1 POINT (-110.7263 34.86508)
2 POINT (-111.7345 38.64123)
3 POINT (-120.1531 46.65593)
4 POINT (-121.7663 39.37335)

要测试交叉点:

> st_intersects(states, pts)
although coordinates are longitude/latitude, st_intersects assumes that they are planar
Sparse geometry binary predicate list of length 9, where the predicate was `intersects'
 1: 1
 2: 4
 3: (empty)
 4: (empty)
 5: (empty)
 6: (empty)
 7: (empty)
 8: 2
 9: 3

该对象是一个列表,因此您可以获取元素的长度并查找大于零的元素-即其中存在某些内容:

> lengths(st_intersects(states, pts)) > 0
although coordinates are longitude/latitude, st_intersects assumes that they are planar
[1]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE

,然后以常规方式对空间多边形进行子集化:

 > plot(st_geometry(states[lengths(st_intersects(states, pts)) > 0,]))

绘制具有四个点的四个状态。

enter image description here

如果这是绘制地图的方式,则创建子集并将其提供给ggplot

答案 1 :(得分:2)

没有示例数据,这是我能想到的最好的方法。

library( sf )

#find intersecting points/polygons    
intersect <- st_intersection(x = polygons, y = points)

#and go further from there

更新

使用答案中提供的@Spacedman示例数据。

library(dplyr)
library(sf)

states %>% 
  #create ID's for the states (if they don't have one already) 
  #state ID should be equal to rownumber (fot the filter later on)
  mutate( id = row_number() ) %>%
  #filter out states that do not have any intersetcions with the points/cities
  filter( id %in% unlist( st_intersects(cities, states) ) ) %>%
  #plot
  mapview::mapview()   

enter image description here