2017-06-21 71 views
1

我有一個igraph對象中每個頂點的郵編。我想使用ggmap將它們轉換成地理座標,這樣我就可以計算邊緣屬性=地理距離。使用ggmap進行地理編碼igraph頂點屬性

require(igraph) 
require(ggmap) 

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

我想我可以生成每個頂點的地理座標是這樣的:

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

結果latlon的座標列表所有頂點重複每個頂點,而不是每一個獨特的latlon頂點。

head(head(V(g)$coordinate) 
[[1]] 
[1] 28.03837 28.31993 31.02204 30.36661 24.91015 28.18540 

[[2]] 
[1] -26.18825 -25.84222 -29.84962 -29.65119 -34.05067 -25.74895 

[[3]] 
[1] 28.03837 28.31993 31.02204 30.36661 24.91015 28.18540 

[[4]] 
[1] -26.18825 -25.84222 -29.84962 -29.65119 -34.05067 -25.74895 

[[5]] 
[1] 28.03837 28.31993 31.02204 30.36661 24.91015 28.18540 

[[6]] 
[1] -26.18825 -25.84222 -29.84962 -29.65119 -34.05067 -25.74895 

-ve numbers = latitude,+ ve numbers = longitude。我究竟做錯了什麼?

+0

geocode爲每個郵政編碼創建一個元組列表。每個元組都包含一個緯度和經度值。 – user2995175

回答

1

問題是geocode返回一個數據幀,但是當您將它分配給V(g)$coordinate時,它將它視爲一個列表,並且循環使用列以獲取每個頂點的值。

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

postcode_df 
#  lon  lat 
# 1 28.03837 -26.18825 
# 2 28.31993 -25.84222 
# 3 31.02204 -29.84962 
# 4 30.36661 -29.65119 
# 5 24.91015 -34.05067 
# 6 28.18540 -25.74895 

您需要將數據幀的每一行都轉換爲可分配給頂點的元素。這可以通過很多方式完成,這裏有一個簡單的方法:

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

V(g)$coordinate 
# [[1]] 
# lon  lat 
# 1 28.03837 -26.18825 
# 
# [[2]] 
# lon  lat 
# 2 28.31993 -25.84222 
# 
# [[3]] 
# lon  lat 
# 3 31.02204 -29.84962 
# 
# [[4]] 
# lon  lat 
# 4 30.36661 -29.65119 
# 
# [[5]] 
# lon  lat 
# 5 24.91015 -34.05067 
# 
# [[6]] 
# lon  lat 
# 6 28.1854 -25.74895 
相關問題