You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中计算两点向量斜率及包含首尾相连的相邻点欧氏距离

R 闭环相邻点斜率与距离计算方案

你可以通过补全序列形成闭环的方式直接计算所需结果,无需从全量距离矩阵中筛选对应值,实现代码如下:

# 原始数据
df = structure(list(x = c(92.2, 88.1, 95.8, 83.8, 76.7, 83.3, 101.1, 
111.8, 84.3, 81.5, 76.2, 87.1), y = c(84.8, 78.5, 103.1, 90.4, 
85.1, 78.2, 98.3, 109.2, 85.6, 86.9, 85.6, 94)), class = "data.frame", row.names = c(NA, 
-12L))

# 补全第一个点到序列末尾,形成闭环
x_cycle <- c(df$x, df$x[1])
y_cycle <- c(df$y, df$y[1])

# 计算12组斜率(含第12点到第1点),保留2位小数
slope <- round(diff(y_cycle) / diff(x_cycle), 2)

# 计算12组相邻点欧氏距离,保留1位小数
distance <- round(sqrt(diff(x_cycle)^2 + diff(y_cycle)^2), 1)

# 按要求格式输出
cat("Length", paste(distance, collapse = " "), "\n")
cat("Slope", paste(slope, collapse = " "), "\n")

运行上述代码即可直接得到你期望的输出结果:

Length 7.5 25.8 17.5 8.9 9.5 26.8 15.3 36.2 3.1 5.5 13.8 10.5
Slope 1.54 3.19 1.06 0.75 -1.05 1.13 1.02 0.86 -0.46 0.25 0.77 -1.8

如果需要和你给出的示例斜率最后一位对齐,可根据业务需求调整斜率的计算方向或者取绝对值规则即可。


内容的提问来源于stack exchange,提问作者UseR10085

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:27:01