我有解決方案現在...即使它是不是很有效。 也許有人認爲這很有用。 我改變了P的座標以獲得更好的結果。
distance <- data.frame(dist = NA)
coordinates <- data.frame(x=NA,y=NA)
coords <- data.frame(x=c(2140,2162,2169,2167,2158),y=c(1466,1437,1412,1390,1369))
point <- data.frame(x=2130,y=1400)
for(j in 1:(length(coords[,1]))){
distance[2*j-1,1] <- sqrt((coords[j,1]-point[1,1])^2+(coords[j,2]-point[1,2])^2)
coordinates[2*j-1,] <- coords[j,]
}
計算從點P的所有垂直距離和點P的這些趴在分割行
for(j in 1:(length(coords[,1])-1)){
d <- abs((coords[j+1,1]-coords[j,1])*(coords[j,2]-point[1,2])-
(coords[j,1]-point[1,1])*(coords[j+1,2]-coords[j,2]))/
sqrt((coords[j+1,1]-coords[j,1])^2+(coords[j+1,2]-coords[j,2])^2)
t <- abs(((point[1,1]-coords[j,1])*(coords[j+1,1]-coords[j,1])+
(point[1,2]-coords[j,2])*(coords[j+1,2]-coords[j,2]))/
((coords[j+1,1]-coords[j,1])^2+(coords[j+1,2]-coords[j,2])^2))
x <- coords[j,1]+t*(coords[j+1,1]-coords[j,1])
y <- coords[j,2]+t*(coords[j+1,2]-coords[j,2])
if(min(coords$x[j],coords$x[j+1]) <= x && x <= max(coords$x[j],coords$x[j+1]) &&
min(coords$y[j],coords$y[j+1]) <= y && y <= max(coords$y[j],coords$y[j+1])){
if(coords[j,] != c(x,y) && coords[j+1,] != c(x,y)){
distance[2*j,1] <- d
coordinates[2*j,] <- c(x,y)
}
}
}
位置最小距離」的座標:
p <- which(distance==min(distance, na.rm=TRUE))
coordinates[p,]
你知道會是什麼太棒了?帶有樣本輸入和期望輸出的[可重現示例](http://stackoverflow.com/questions/5963269/how-to-make-a- great-r-reproducible-example)。只是要求包裹建議被認爲是SO的主題。 – MrFlick 2014-09-12 15:20:13
使用標準幾何圖形來查找從點到實線的距離,然後如果該點不在一個線段上,請找到最接近的線段端點。這與'R'無關。 – 2014-09-12 15:45:38
如果你發佈公式,你更有可能得到如何把它放在代碼中。 – rnso 2014-09-12 15:56:20