R 如何在SPDF中使用距离对多边形子集

R 如何在SPDF中使用距离对多边形子集,r,choropleth,spdf,R,Choropleth,Spdf,嗯。所以,当我10天前还没有学会a是什么的时候,我正在学习并提出了一个非常类似的问题: 现在,我发现了SPDF和choropleth地图的魔力,本质上有相同的问题,但文件类型不同。我仍然在用头脑去思考S4对象,我不知道如何从我的数据集中对某些迷你多边形MUNICIPI进行子集划分 切中要害 上下文: 我有一个包含以下数据的SPDF: 目标: 我想对距离海岸一定距离内的所有市政进行子集划分。假设@urbandatascientist在回答我的第一个问题时设置了20公里,并创建了一个choropl

嗯。所以,当我10天前还没有学会a是什么的时候,我正在学习并提出了一个非常类似的问题:

现在,我发现了SPDF和choropleth地图的魔力,本质上有相同的问题,但文件类型不同。我仍然在用头脑去思考S4对象,我不知道如何从我的数据集中对某些迷你多边形
MUNICIPI
进行子集划分

切中要害

上下文: 我有一个包含以下数据的SPDF:

目标:

我想对距离海岸一定距离内的所有
市政
进行子集划分。假设@urbandatascientist在回答我的第一个问题时设置了20公里,并创建了一个choropleth地图,例如,
上层树
,子集为
市政

在这篇文章中,我还提供了
多边形边界列表
,我们将从中减去
市政坐标

一旦我将海岸
城市划分为子集,我希望地图看起来会很像,我还尝试确保.polygon.bounders的列表之间的坐标相同

任何线索或想法都将不胜感激

到目前为止,以下是我使用
上部_树作为示例绘制的整个区域的叶绿体图:

tm_形(catasense2)+
tm_fill(col=“上_树”,n=8,style=“分位数”)+
tm_布局(legend.outside=TRUE)

概述 与的答案类似,解决方案包括以下步骤:

  • 计算巴利阿里(伊比利亚海)和地中海西部盆地西部边界的坐标

  • 从OP的链接到她的Google Drive文件夹(其中包含形状文件的.zip文件),计算
    MUNICIPI
    中每个多边形的质心

  • 计算前两个点和子集
    市政
    之间的距离,以显示从其质心到西部盆地的距离小于或等于20公里的多边形

过滤西部盆地的坐标 我没有计算每个质心到
western.basin.polygon.coordinates
中每个坐标对的距离,而是只包括
western.basin.polygon.coordinates
中纬度点位于加泰罗尼亚东海岸之间(含)的坐标

作为参考,我使用和的纬度点。通过仅保留沿加泰罗尼亚东海岸的坐标对,
西部盆地多边形坐标
市政
中每个质心之间的距离计算大约在4分钟内完成

然后,我在
小于或等于.max.km
中存储了
市政
内多边形的索引,这些多边形的质心距离小于或等于20 km,这是真/假值的逻辑向量。使用地图,我展示了如何将
市政
子集化,以仅可视化那些包含
小于或等于.max.km的真值的多边形

# load necessary packages
library( geosphere )
library( leaflet )
library( sf )

# load necessary data
unzip( zipfile = "catasense2-20180327T023956Z-001.zip" )

# transfrom zip file contents
# into a sf data frame
MUNICIPI <-
  read_sf(
    dsn = paste0( getwd(), "/catasense2" )
    , layer = "catasense2"
  )


# map data values to colors
my.color.factor <- 
  colorFactor( palette = "viridis", domain = MUNICIPI$uppr_tr )

# Visualize
leaflet( data = MUNICIPI ) %>%
  setView( lng = 1.514619
           , lat = 41.875227
           , zoom = 8 ) %>%
  addTiles() %>%
  addPolygons( color = ~my.color.factor( x = uppr_tr ) )

在我这方面,还不清楚确切的问题:目标是从空间多边形数据框中仅子集那些距离海岸线最大20公里的多边形?@Seymour hi!对不起,你没弄清楚。我已经做了更精确的编辑。但你是对的。将这些多边形中的数据子集,并仅将其绘制到地图上。看看我添加到他们地图上的链接,理想的样子。但是你如何定义海岸线呢?因为除非这个空间多边形框架是一个岛屿,否则一些外部边界在内陆领土上,而另一些在沿海领土上。@Seymour-Excellent point-Seymour。这一点在中得到了准确的回答,这就是我在这个问题中所指的
list.of.polygon.bounders
,它位于data.Perfect中,那么一个可能的解决方案就是
gDistance()
rGeos
包的
function。该函数将接收两个输入:“海岸多边形”和整个空间多边形框架。此函数计算每个“沿海多边形”和SPDF的每个多边形之间的距离(因为我们正在谈论西班牙),单位为米。输出是一个RxC矩阵,其中每行是“沿海多边形”的ID,每列是SPDF的ID,每个单元格是两个空间对象之间的距离(以米为单位)。然后,你可以简单地
过滤
只保留那些
距离<20000的人
亲爱的@aspiringurbandatascientist,我非常仔细地检查了这一点,并且能够运行它!谢谢你详细解释一切。我有几个问题,但不是很紧急:summit.east.west.lat.max.condition=east.west.lat.range[“东”]&I[,“Y”]还有:western.basin.polygon.coordinates@delcast没问题。对于您的第一个评论,我将
western.basin.polygon.coordinates
子集化,以仅返回满足不等式的纬度指数(通过
I[,“Y”]
)。我们不使用“X”,因为它代表经度。对于您的第二条评论,我们使用新创建的
满足.east.west.lat.max.condition
mapply()
中过滤
western.basin.polygon.coordinates
中的每个列表,同时保留一个列表;而
sapply()
返回一个向量或矩阵。根据您的分析,我已经删除了以前的注释。对我来说,我看到了两个输入,并且自然地思考,因为这是一个多变量版本的。现在我很想知道另一种方法,来找出
MUNICIPI
中哪些多边形距离海岸线不到或等于20公里。我删除了我的多边形,因为错误实际上是:“I[j]中的错误:无效的下标类型‘列表’”。
# unzip the western basin zip file
# unzip( zipfile = "iho.zip" )

# create sf data frame
# of the western basin
western.basin <-
  read_sf( dsn = getwd()
           , layer = "iho"
           , stringsAsFactors = FALSE )

# filter the western.basin
# to only include those bodies of water
# nearest catalonia
water.near.catalonia.condition <-
  which( 
    western.basin$name %in% 
      c( "Balearic (Iberian Sea)"
         , "Mediterranean Sea - Western Basin" )
    )

western.basin <-
  western.basin[ water.near.catalonia.condition, ]

# identify the coordinates for each of the
# remaining polygons in the western.basin
# get the boundaries of each
# polygon within the western basin
# and retain only the lon (X) and lat (Y) values
western.basin.polygon.coordinates <-
  lapply( 
    X = western.basin$geometry
    , FUN = function( i )
      st_coordinates( i )[ , c( "X", "Y" ) ]
  )

# find the centroid
# of each polygon in MUNICIPI
MUNICIPI$centroids <-
  st_centroid( x = MUNICIPI$geometry )

# Warning message:
#   In st_centroid.sfc(x = MUNICIPI$geometry) :
#   st_centroid does not give correct centroids for longitude/latitude data

# store the latitude
# of the western (Peniscola, Catalonia) and eastern (Cerbere, France) 
# most parts of the eastern coast of Catalonia
east.west.lat.range <- 
  setNames( object = c( 40.3772185, 42.4469981 )
            , nm = c( "east", "west" )
  )

# set the maximum distance
# allowed between a point in df
# and the sea to 20 kilometers
max.km <- 20

# store the indices in the
# western basin polygon coordinates whose
# lat points
# fall in between (inclusive) 
# of the east.west.lat.range
satisfy.east.west.lat.max.condition <-
  lapply(
    X = western.basin.polygon.coordinates
    , FUN = function(i)
      which(
        i[, "Y"] >= east.west.lat.range["east"] &
          i[, "Y"] <= east.west.lat.range["west"]
      )
  )

# filter the western basin polygon coordinate
# by the condition
western.basin.polygon.coordinates <-
  mapply(
    FUN = function( i, j )
      i[ j, ]
    , western.basin.polygon.coordinates
    , satisfy.east.west.lat.max.condition
  )

# calculate the distance of each centroid
# in MUNICIPI
# to each point in both western.basin
# polygon boundary coordinates
# Takes ~4 minutes
distance <-
  apply(
    X = do.call( what = "rbind", args = MUNICIPI$centroids )
    , MARGIN = 1
    , FUN = function( i )
      lapply(
        X = western.basin.polygon.coordinates
        , FUN = function( j )
          distGeo(
            p1 = i
            , p2 = j
          ) / 1000 # to transform results into kilometers
      )
  )

# 1.08 GB list is returned
object.size( x = distance)
# 1088805736 bytes

# find the minimum distance value
# for each list in distance
distance.min <-
  lapply(
    X = distance
    , FUN = function( i )
      lapply(
        X = i
        , FUN = function( j )
          min( j )
      )
  )

# identify which points in df
# are less than or equal to max.km
less.than.or.equal.to.max.km <-
  sapply(
    X = distance.min
    , FUN = function( i )
      sapply(
        X = i
        , FUN = function( j )
          j <= max.km
      )
  )

# convert matrix results into
# vector of TRUE/FALSE indices
less.than.or.equal.to.max.km <-
  apply(
    X = less.than.or.equal.to.max.km
    , MARGIN = 2
    , FUN = any
  )

# now only color data that meets
# the less.than.or.equal.to.max.km condition
leaflet( data = MUNICIPI[ less.than.or.equal.to.max.km, ] ) %>%
  setView( lng = 1.514619
           , lat = 41.875227
           , zoom = 8 ) %>%
  addTiles() %>%
  addPolygons( color = ~my.color.factor( x = uppr_tr ) ) 

# end of script #
R version 3.4.4 (2018-03-15)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.2

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base     

other attached packages:
[1] sf_0.6-0           leaflet_1.1.0.9000 geosphere_1.5-7   

loaded via a namespace (and not attached):
 [1] mclust_5.4         Rcpp_0.12.16       mvtnorm_1.0-7     
 [4] lattice_0.20-35    class_7.3-14       rprojroot_1.3-2   
 [7] digest_0.6.15      mime_0.5           R6_2.2.2          
[10] plyr_1.8.4         backports_1.1.2    stats4_3.4.4      
[13] evaluate_0.10.1    e1071_1.6-8        ggplot2_2.2.1     
[16] pillar_1.2.1       rlang_0.2.0        lazyeval_0.2.1    
[19] diptest_0.75-7     whisker_0.3-2      kernlab_0.9-25    
[22] R.utils_2.6.0      R.oo_1.21.0        rmarkdown_1.9     
[25] udunits2_0.13      stringr_1.3.0      htmlwidgets_1.0   
[28] munsell_0.4.3      shiny_1.0.5        compiler_3.4.4    
[31] httpuv_1.3.6.2     htmltools_0.3.6    nnet_7.3-12       
[34] tibble_1.4.2       gridExtra_2.3      dendextend_1.7.0  
[37] viridisLite_0.3.0  MASS_7.3-49        R.methodsS3_1.7.1 
[40] grid_3.4.4         jsonlite_1.5       xtable_1.8-2      
[43] gtable_0.2.0       DBI_0.8            magrittr_1.5      
[46] units_0.5-1        scales_0.5.0       stringi_1.1.7     
[49] reshape2_1.4.3     viridis_0.5.0      flexmix_2.3-14    
[52] sp_1.2-7           robustbase_0.92-8  squash_1.0.8      
[55] RColorBrewer_1.1-2 tools_3.4.4        fpc_2.1-11        
[58] trimcluster_0.1-2  DEoptimR_1.0-8     crosstalk_1.0.0   
[61] yaml_2.1.18        colorspace_1.3-2   cluster_2.0.6     
[64] prabclus_2.2-6     classInt_0.1-24    knitr_1.20        
[67] modeltools_0.2-21