Re: [問題] 使用lmap::gdist找兩組資料最近點的錯誤

作者: cywhale (cywhale)   2017-10-26 23:46:49
試試看這是不是你要的,沒有再試其他方法,可能有更快的解法..
如果不要那個 偵測 > 5 的criteria, 可以不要那些if else 直接回傳which.min
library(data.table)
library(Imap)
data <- fread('Lon Lat
100.7200 13.61500
100.6683 13.52000
100.5717 13.54500
100.5750 13.69333
100.5783 13.82333
100.3983 13.90833')
mindst <- function(i,x,y,criteria=NA) {
y$id <- seq_len(nrow(y))
if(!is.na(criteria)) {
idx <- which(y$Lon<=x$Lon[i]+criteria & y$Lat<=x$Lat[i]+criteria)
if (!any(idx)) {
return(0L)
}
y <- y[idx,]
}
y$id[which.min(sapply(1:nrow(y),function(j) {
gdist(x$Lon[i],x$Lat[i],
y$Lon[j],y$Lat[j],
units = "nm",verbose = FALSE)} ))]
}
set.seed(123L)
temp <- data.table(Lon=100.0+sample.int(1000,size=1000, replace=T)/100,
Lat=10.0+sample.int(100,size=1000, replace=T)/10)
system.time(out1 <- sapply(1:nrow(data),mindst, x=data, y=temp))
system.time(out2 <- sapply(1:nrow(data),mindst, x=data, y=temp, criteria=5))
#> system.time(out1 <- sapply(1:nrow(data),mindst, x=data, y=temp))
# user system elapsed
# 0.86 0.00 0.86
#>
#> system.time(out2 <- sapply(1:nrow(data),mindst, x=data, y=temp, criteria=5))
# user system elapsed
# 0.41 0.00 0.40
#> out1
#[1] 289 289 289 289 326 326
#> out2
#[1] 289 289 289 289 326 326
※ 引述《giock18 (小武)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來)
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 我有兩組經緯度座標,每組資料長得像這樣
: data$Lon data$Lat
: 100.7200 13.61500
: 100.6683 13.52000
: 100.5717 13.54500
: 100.5750 13.69333
: 100.5783 13.82333
: 100.3983 13.90833
: 另一組稱為temp
: temp$Lon & temp$Lat
: 其中一組是參考地標的經緯度,另外一組是實際的軌跡
: 我使用gdist來算出點和點之間的距離,並找最小值,
: 也就是最靠近這個地標的點。
: 因此我的程式碼這樣寫
: for (i in nrow(data)){
: closest<-which.min(gdist(data$Lon[i],
: OFPdata$Lat[i],temp$LONGITUDE,temp$LATITUDE,units = "nm",verbose = FALSE) )}
: 用迴圈的方式去找每個地標對應到的最靠近軌跡
: which.min雖然有用,但是應該是因為原本lmap::gdist的設計是輸入單值,
: 但我卻給他一欄資料,所以他會跳出警告如下,雖然程式還是可以work,
: 但想知道有沒有更正確的寫法?
: Warning messages:
: 1: In while (abs(lamda - lamda.old) > 1e-11) { :
: the condition has length > 1 and only the first element will be used
: 2: In while (abs(lamda - lamda.old) > 1e-11) { :
: the condition has length > 1 and only the first element will be used
: 另外,為了提升程式的效率,想要將軌跡與地標的計算迭代縮小成
: 經度或緯度差5度以內的才計算,不知道有甚麼方法可以達成呢?
: 我有在stackoverflow發問,原文網址如下:
: https://stackoverflow.com/questions/46843802/find-the-nearest-point-using-lmapgdist-function
: 先謝謝了
: [環境敘述]:
: R version 3.4.1 (2017-06-30)
: Platform: x86_64-w64-mingw32/x64 (64-bit)
: Running under: Windows >= 8 x64 (build 9200)
: [關鍵字]:
: lmap,gdsit,nearest point,closer point,經緯度距離
作者: giock18 (小武)   2017-10-28 15:47:00
太感謝了 !!!

Links booklink

Contact Us: admin [ a t ] ucptt.com