2017-02-16 111 views
0

我查看了其他問題,例如this,thisthis,但所有這些都計算到由兩個端點定義的線段的最短距離,而我沒有能夠做同樣的事情,但對於由攔截和斜坡定義的線。計算由截距和斜率在R中定義的點到線的最短距離

這是我的數據,我繪製並添加一條線,總是有一個截距爲0,斜率由兩個變量定義。

df <- data.frame(x = seq(1, 10, 1), 
       y = seq(1, 10, 2), 
       id = head(letters, 10)) 

plot(df$x, df$y, 
    abline(a = 0, b = (mean(df$x)/mean(df$y))))  

我想計算從每個點到線的最短距離。

+1

這也許可以回答你的問題: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line – echasnovski

回答

1

測試此(自here修改)

#Perpendicular distance from point 'a' to a line with 'slope' and 'intercept' 
dist_point_line <- function(a, slope, intercept) { 
    b = c(1, intercept+slope) 
    c = c(-intercept/slope,0)  
    v1 <- b - c 
    v2 <- a - b 
    m <- cbind(v1,v2) 
    return(abs(det(m))/sqrt(sum(v1*v1))) 
} 

dist_point_line(c(2,1), 1, 0) 
#[1] 0.7071068 

在你的情況,你可以做這樣的事情

apply(df, 1, function(x) dist_point_line(as.numeric(x[1:2]), slope = 1, intercept = 0)) 
#[1] 0.0000000 0.7071068 1.4142136 2.1213203 2.8284271 3.5355339 2.8284271 2.1213203 1.4142136 0.7071068 
+1

它看起來很完美。謝謝你的答案。 –