2016-11-20 46 views
1

我有兩個數據集 - 我們稱之爲'plot'(734行)和'stations'(62 rows)。前一段時間,我發現這段代碼應該讓我根據座標將每個'plot'鏈接到離它最近的'station'R - 連接兩組不同的座標

數據集有點像這樣 - (但沒有Long和Lat的標題)

plot - Long Lat   stations - Long Lat 
     13.2 60.5     14.6 55.4 
     15.4 62.6     15.5 62.9 
     15.6 62.4     16.4 58.9 
     16.5 58.7     19.3 64.0 
     16.5 58.5 


#print results to "results.csv" 
sink("results.csv") 

#identifyl long + lat coords of each data set 
p_coord<-SpatialPoints(plot[,c(1,2)]) 
s_coord<-SpatialPoints(stations[,c(1,2)]) 

#link coordinates 
require(FNN) 
g = get.knnx(coordinates(s_coord), coordinates(p_coord),k=1) 
str(g) 
plot(s_coord_2, col=2, xlim=c(-1e5,6e5)) 
plot(p_coord, add=TRUE) 
segments(coordinates(p_coord)[,1], coordinates(p_coord)[,2], coordinates(s_coord[g$nn.index[,1]])[,1], coordinates(s_coord[g$nn.index[,1]])[,2]) 

#print result in results.csv 
print(g) 

我已經意識到我得到的結果有點不對 - 例如圖#3和#4與#4站相關,當它更適用於圖#4和#5鏈接時到#4站。

因此,這使我覺得這事在代碼稍微偏離,但只有一排

想知道關於我的代碼有任何意見,還是我有着同樣的興趣插入簡單的方法建議,以連接兩個系列座標 謝謝

+0

「地塊#4和#5鏈接到站#4」。..應該不是站#3? –

回答

0

什麼是您的座標參考系?這些點在斯堪的納維亞? 無論如何,你可以與岩石圈包去使用distHaversinedistVincentyEllipsoid(更精確的),以獲得距離:

plot <- data.frame(Lon = c(13.2,15.4,15.6,16.5,16.5), 
        Lat = c(60.5,62.6,62.4,58.7,58.5)) 

stations <- data.frame(Lon = c(14.6,15.5,16.4,19.3), 
         Lat = c(55.4,62.9,58.9,64)) 

p_coord <- SpatialPoints(plot[,c(1,2)]) 
s_coord <- SpatialPoints(stations[,c(1,2)]) 

library(geosphere) 
apply([email protected], 1, function(x) { 
    which.min(distHaversine(p1 = x, p2 = [email protected])) 
}) 

輸出將是

[1] 3 2 2 3 3 

這意味着地塊1接近到第3站,第2小區與第2站相連,依此類推。