【问题标题】:Calculating geographic distance of edge in iGraph在 iGraph 中计算边缘的地理距离
【发布时间】:2017-06-22 05:04:32
【问题描述】:

我有 iGraph 对象中每个顶点的地理坐标。现在我想计算现有边缘之间的距离。

library(igraph)
library(ggmap)
library(geosphere)

g <- graph.ring(6)
V(grph)$postcode <- c("Johannesburg 2017", 
                  "Rondebosch 8000",
                  "Durban 4001", 
                  "Pietermaritzburg 3201", 
                  "Jeffreys Bay 6330", 
                  "Pretoria 0001" )

postcode_df <- geocode(V(g)$postcode, sensor = FALSE, 
                       output = "latlon", source = "google")

V(g)$coordinate <- split(postcode_df, 1:nrow(postcode_df))

V(g)$coordinate[1]
[[1]]
       lon       lat
1 28.03837 -26.18825

我想使用这种通用方法计算距离:

el <- get.edgelist(g, names=FALSE)
E(g)$distance <- distHaversine(V(g)$coordinate[[el[,1]]],V(g)$coordinate[[el[,2]]])

问题是 V(g)$coordinate 中的 lon 和 lat 不能这样引用。我的递归索引在第 3 级失败。显然我不能将一个数据帧的索引嵌套在另一个数据帧中。

str(V(g)$coordinate)
List of 6
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 28
  ..$ lat: num -26.2
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 28.3
  ..$ lat: num -25.8
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 31
  ..$ lat: num -29.8
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 30.4
  ..$ lat: num -29.7
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 24.9
  ..$ lat: num -34.1
 $ :'data.frame':   1 obs. of  2 variables:
  ..$ lon: num 28.2
  ..$ lat: num -25.7

计算两点之间距离的一般方法是

distHaversine(p1, p2, r=6378137).

p1 由 el[,1] 定义,p2 由 el[,2] 定义。 el[,1:2] 指的是 g 中的顶点数。所以需要提取el[,1]和el[,2]对应的V(g)$坐标。建议将不胜感激。

【问题讨论】:

    标签: r igraph ggmap geosphere


    【解决方案1】:

    这里有一个问题,split 正在返回一个数据帧,我们可以通过以下方式修复:

    V(g)$coordinate <- lapply(split(postcode_df, 1:nrow(postcode_df)), unlist)
    

    那么您实际上需要遍历两个列表,即每个顶点的坐标。

    使用来自purrrmap2 很容易。

    library(purrr)
    el <- get.edgelist(g, names=FALSE)
    E(g)$distance <- unlist(map2(V(g)$coordinate[el[,1]], V(g)$coordinate[el[,2]], distHaversine))
    

    【讨论】:

    • 这在嵌套列表中提供了答案。我需要取消嵌套所有内容,以便 E(g)$distance 返回一个值列表。
    • g
    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 2021-12-28
    • 2017-06-25
    • 2012-12-25
    • 2018-05-03
    • 2017-05-28
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多