简体   繁体   English

sf package 读取 st_within 的 shapefile

[英]sf package read shapefile for st_within

I'm trying to use st_within to find points within a polygon, but I can't get a shapefile into the right format.我正在尝试使用 st_within 来查找多边形内的点,但我无法将 shapefile 转换为正确的格式。 I'm using the standard shp file JPN_adm1.shp from https://purl.stanford.edu/np872wp5062 or https://gadm.org/download_country.html我正在使用来自https://purl.stanford.edu/np872wp5062https://gadm.org/download_countryC76A235FDC7ADFC22 的标准 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)

The code runs, but it doesn't exclude Tokyo which isn't in Aichi.代码运行,但不排除不在爱知县的东京。 What's wrong?怎么了?

First, you do not need to use the lines of code starting with st_transform() because the JPN and some_point.sf objects are already in WGS84首先,您不需要使用以st_transform()开头的代码行,因为JPNsome_point.sf对象已经在WGS84

Secondly, not sure to fully understand your problem, but I give it a try!其次,不确定是否完全理解您的问题,但我试一试! I guess you just need to set the argument left = FALSE inside the st_join() function.我猜你只需要在st_join() function 中设置参数left = FALSE Otherwise st_join() performs a left join by default.否则st_join()默认执行left join

Please find below a reprex:请在下面找到一个代表:

Reprex代表

  • Code代码
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"
  • Output Output

You get an empty sf object as expected:正如预期的那样,你得到一个空的sf object:

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)

Created on 2022-02-04 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 2 月 4 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM