sf 包读取 st_within 的 shapefile

sf package read shapefile for st_within

我正在尝试使用 st_within 在多边形内查找点,但我无法将 shapefile 转换为正确的格式。我正在使用来自 https://purl.stanford.edu/np872wp5062 or https://gadm.org/download_country.html

的标准 shp 文件 JPN_adm1.shp
JPN <- st_read("JPN_adm1.shp")
JPN <- JPN[1,] ## select one prefecture, Aichi
JPN <- st_transform(JPN, crs="WGS84")

tokyo.df <- data.frame("name"="Tokyo","lat"=35.507,"lon"=139.208)
some_point.sf <- st_as_sf(tokyo.df, coords = c("lon","lat"), crs="WGS84")
some_point.sf <- st_transform(some_point.sf, crs="WGS84")
subset <- st_join(some_point.sf, JPN, join = st_within)

代码运行,但不排除不在爱知县的东京。怎么了?

首先,您不需要使用以st_transform()开头的代码行,因为JPNsome_point.sf对象已经在WGS84[=23=中]

其次,不确定是否完全理解你的问题,但我试一试!我猜你只需要在 st_join() 函数中设置参数 left = FALSE 。否则 st_join() 默认执行 left join(而不是特定情况下所需的 inner join)。

请在下面找到一个代表:

Reprex

  • 代码
library(sf)

JPN <- st_read("JPN_adm1.shp")
JPN <- JPN[1,] ## select one prefecture, Aichi
# JPN <- st_transform(JPN, crs="WGS84")            # NO NEED TO DO THAT

tokyo.df <- data.frame("name"="Tokyo","lat"=35.507,"lon"=139.208)
some_point.sf <- st_as_sf(tokyo.df, coords = c("lon","lat"), crs="WGS84")
# some_point.sf <- st_transform(some_point.sf, crs="WGS84")       # NO NEED TO DO THAT
subset <- st_join(some_point.sf, JPN, join = st_within, left = FALSE) # ADD ARGUMENT "LEFT = FALSE"
  • 输出

你得到了一个空的 sf 对象,正如预期的那样:

subset
#> Simple feature collection with 0 features and 13 fields
#> Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
#> Geodetic CRS:  WGS 84
#>  [1] name      ID_0      ISO       NAME_0    ID_1      NAME_1    HASC_1   
#>  [8] CCN_1     CCA_1     TYPE_1    ENGTYPE_1 NL_NAME_1 VARNAME_1 geometry 
#> <0 lignes> (ou 'row.names' de longueur nulle)

reprex package (v2.0.1)

于 2022-02-04 创建