首页 > 解决方案 > 计算沿线的距离,每个点将相交

问题描述

我想通过随机分布的点中的两个点拟合一条线,然后计算沿该线的每个点与其正交相交的位置。我对每个点与线的剩余距离不感兴趣(线上方/下方的点被同等对待),我只对计算沿该点相交的线的位置感兴趣(例如,距线不同距离的点)但在相同正交位置的线将具有相同的值)。数据没有明确连接到线,因为 abline 仅从 2 个点的位置绘制,因此我无法以经典的残差类型方式提取这些值。我不认为这很困难,但我无法理解如何计算它,这真的让我很烦恼!

我已经探索了 dist2d 函数,但是它计算了每个点到直线的正交距离。有没有办法使用该值来计算从数据点到线上某个固定常数点的斜边,然后再计算与该常数的相邻距离?我真的很感激任何帮助!

#here is some example starter code here to visualise what I mean
#get random data
r = rnorm(100)
t = rnorm(100)
#bind and turn into a df
data = cbind(r,t)
data = as.data.frame(data)
head(data)
#plot
plot(data)

#want to draw abline between 2 points

#isolate points of interest
#here randomly select first two rows
d = data[c(1:2),]
head(d)

#calculate abline through selected points
lm = lm(t ~ r, d)
abline(lm)
#draw points to see which ones they cut through
points(d$r, d$t, bg = "red", pch = 21)

标签: rlinedistancetransformationpoint

解决方案


下面的代码有效。

# Create dataframe
data = data.frame(x = rnorm(100), y = rnorm(100))
plot(data, xlim=c(-3, 3), ylim=c(-3, 3))

# Select two points
data$x1_red <- data[1,1]; data$y1_red <- data[1,2]; data$x2_red <- data[2,1]; data$y2_red <- data[2,2];
points(data$x1_red, data$y1_red, bg = "red", pch = 21); points(data$x2_red, data$y2_red, bg = "red", pch = 21);

# Show a red line where the points intersect
# Get its slope (m_red) and intercept (b_red)
data$m_red <- (data[2,2] - data[1,2]) / (data[2,1] - data[1,1])
data$b_red <- data$y1_red - data$m * data$x1_red
abline(data$b_red, data$m_red, col='red')

# Calculate the orthogonal slope
data$m_blue <- (-1/data$m_red)
abline(0, data$m_blue, col='blue')

# Solve for each point's b-intercept (if using the blue slope)
# y = m_blue * x + b
# b = y - m_blue * x
data$b <- data$y - data$m_blue * data$x

# Solve for where each point (using the m_blue slope) intersects the red line (x' and y')
# y' = m_blue * x' + b
# y' = m_red * x' + b_red
# Set those equations equal to each other and solve for x'
data$x_intersect <- (data$b_red - data$b) / (data$m_blue - data$m_red)
# Then solve for y'
data$y_intersect <- data$m_blue * data$x_intersect + data$b

# Calculate the distance between the point and where it intersects the red line
data$dist <- sqrt( (data$x - data$x_intersect)^2 + (data$y - data$y_intersect)^2 )

推荐阅读