【问题标题】:How to calculate the distance of a centroid to a polygon in a shape file? R如何计算形状文件中质心到多边形的距离? R
【发布时间】:2021-01-30 14:23:36
【问题描述】:

我有这个,我正在尝试使用gDistance 来计算每个质心与巴格达市之间的距离。我正在尝试这样做:

gDistance(districts_centroids, districts@data$ADM3NAME %in% c("Baghdad"), byid=TRUE)

其中district_centroidsFormal Class SpatialPointsdistricts@data... 基本上是shp 文件中的巴格达市。

我收到一条错误消息:

(函数(类,fdef,mtable)中的错误: 无法为签名“逻辑”找到函数“is.projected”的继承方法 另外:警告信息: 在 RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance") 中: 空间对象 1 未投影; GEOS 需要平面坐标

我对 R 完全陌生,我真的不知道发生了什么。

任何帮助将不胜感激

谢谢!

【问题讨论】:

  • 嗨!您能否分享数据并创建一个reproducible example
  • 嗨。我相信我已经按照描述回答了您的问题。如果此答案有帮助,请单击答案旁边的向上箭头。问候,

标签: r sp


【解决方案1】:

这是一个很好的问题。看了之后,决定回答这个问题的最好方法是使用simple feature objects而不是空间对象。

有问题的地图看起来很熟悉。我使用了IRQ_2_sf.rds 地图,这可能与上面使用和显示的地图相同。还有其他替代方法可以解决这个问题。 Jupyter Lab 是使用的 IDE。

使用 Google API 和 geocode 函数,检索到巴格达的坐标。

baghdad <- geocode("Baghdad, Iraq", source = c("google") )

A tibble: 1 × 2
 lon         lat
<dbl>       <dbl>
44.36607    33.31524

然后使用sf 函数创建sf column object

baghdad.sfg <- st_point(c(lon, lat), dim = "XY")
baghdad.sfc <- st_sfc(baghdad.sfg, crs = 4326)

然后,使用名为 iraq 的 SF 地图,创建了 centroids。 注意:警告消息 - st_centroid 没有为经度/纬度数据提供正确的质心。对于这个答案,质心将接近 够了。

iraq.c <- st_centroid(iraq)

每个centroid 到巴格达的距离以公里为单位确定。

head(dist <- data.frame(c(st_distance(iraq.c$geom[], baghdad.sfc)/1000)))

Units: [m]
[1]  28.63250  59.61553 215.43354 323.06418 259.14509 113.55356

然后创建一个包含名称、centroid 几何和距离值的日期框架。需要一些清洁和绑定。

distance <- c(dist$c.st_distance.iraq.c.geom....baghdad.sfc..1000.)

x <- distance[]
d_Bdad_Km <- as.numeric(str_extract(x, "[0-9]*.[0-9]."))

iraq2 <- iraq[-c(5, 8,9,10,11,12,13)] 
df_dist <- cbind(iraq2, d_Bdad_Km)      # df as desired

然后输出得到plotted

plot(iraq$geom)
plot(iraq.c$geom, add = TRUE, col = "red")
plot(baghdad.sfc, add = TRUE, pch = 19, col = "blue")

请询问是否有任何后续问题。剧情可以看这个link:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2020-03-28
    • 2013-11-14
    • 2014-06-28
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多