又发现了sf包一个强大的工具,鹅妹子哦。记录一下。
本次的case是遍历提取多个区县的相邻区县名称,sf包的st_touches能非常简单的实现该功能。
我们先看下函数说明,专门的说明似乎只有写在cheat sheet里:
![e5caa2058a6f4a88129c9453dc0402e7.png](https://i-blog.csdnimg.cn/blog_migrate/2c221f2d1f1c3e8c2423161978d09706.png)
老实说我是没看懂,我觉得不熟悉GIS的人看到这个说明应该也是懵逼的,我也只是根据函数名称误打误撞猜到这个用法。
下面展示下示例:
library(sf)
#读入shp数据
county<-st_read('区县polygon.shp',
stringsAsFactors = FALSE)
>#提取一个区县数据
> subcounty<-county[50,]
>
>#打印一下,提取的是石家庄市元氏县的数据
> subcounty
Simple feature collection with 1 feature and 9 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: 114.1752 ymin: 37.67184 xmax: 114.6366 ymax: 37.92676
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
AdminCode Kind CityAdCode ProAdCode Name CityName ProName Shape_Leng Shape_Area
50 130132 0137 130100 130000 元氏县 石家庄市 河北省 1.442918 0.06901301
geometry
50 MULTIPOLYGON (((114.529 37....
>
>#使用st_touches提取与元氏县相交的county内的要素的index
> st_touches(subcounty,county)
although coordinates are longitude/latitude, st_touches assumes that they are planar
Sparse geometry binary predicate list of length 1, where the predicate was `touches'
1: 39, 40, 41, 45, 47, 51
>
>#注意,上面传回的是county数据的index,也就是第几行,以list的形式储存,
>#由于subcounty只有一个要素,传回的数据只有一个list
>
>#因此与元氏县相交的区县名称可以这么提取:
> county[unlist(st_touches(subcounty,county)),]$Name
although coordinates are longitude/latitude, st_touches assumes that they are planar
[1] "鹿泉区" "栾城区" "井陉县" "高邑县" "赞皇县" "赵县"
没了,就是这么简单。各位可以自己搜一下,与元氏县相邻的区县名称是不是如上面显示的那样。
至于处理多个区县,不会用lapply的话写个for循环遍历一下county里所有区县也是可以的,会lapply的话,直接x跟y都设置成county,再lapply处理所有list,这样函数看起来更简洁。