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