r - 计算沿线的距离,每个点将相交
问题描述
我想通过随机分布的点中的两个点拟合一条线,然后计算沿该线的每个点与其正交相交的位置。我对每个点与线的剩余距离不感兴趣(线上方/下方的点被同等对待),我只对计算沿该点相交的线的位置感兴趣(例如,距线不同距离的点)但在相同正交位置的线将具有相同的值)。数据没有明确连接到线,因为 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)
解决方案
下面的代码有效。
# 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 )
推荐阅读
- javascript - 如何在没有表单的情况下将文本文件上传到nodejs
- haproxy - 拒绝访问 HAproxy 中的 URI
- android - 在 AlertDialog 上使用 CustomLayout
- javascript - 将 s3 图像转换为画布
- python - 大熊猫平均时间戳之间的数据
- google-maps-api-3 - 从 KML 加载的多边形是否包含 Google Maps API 中的给定 Lat/Lng
- security - .Net 4.5.2 框架是否支持带有 URL 重写的 Samesite cookie
- types - F# 中带有语句的跨类型记录?
- php - woocommerce 删除所有标签,在页面上显示其内容
- python - requests.patch() 返回 200 OK 但没有任何变化