繁体   English   中英

如何计算 r 中两个向量的斜率和距离?

[英]How to calculate slope and distance of two vectors in 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 <- df$x
y <- df$y

#Slope
diff(y)/diff(x)

#Distance
dist(df, method = "euclidean")

您可以在斜率的 output 中看到 11 个值即将到来。 我也想要 12-1 的斜率。 我怎么能得到那个? 和距离 output 我只想要 1-2、2-3、3-4、4-5、5-6、6-7、7-8、8-9、9-10、10-11 的值, 11-12 和 12-1 组合。 我怎样才能实现它? 预期的 output 是

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.08

没有很好的diff function 来获取最后一个向量元素和第一个向量元素的差异,您可以直接使用(y[12] - y[1]) / (x[12] - x[1]) ,或者如果你想更一般地使用tail(x, 1)作为最后一个元素,使用head(x, 1)作为第一个元素。 直接计算它并将 append 计算为您的slope向量。

对于连续点的欧式距离,直接计算它最直接: distance = sqrt(diff(x)^2 + diff(y)^2)

(slope = c(diff(y)/diff(x), (head(y, 1) - tail(y, 1)) / (head(x, 1) - tail(x, 1))))
# [1]  1.5365854  3.1948052  1.0583333  0.7464789 -1.0454545  1.1292135  1.0186916
# [8]  0.8581818 -0.4642857  0.2452830  0.7706422 1.8039216

(distance = sqrt(diff(x)^2 + diff(y)^2))
# [1]  7.516648 25.776928 17.472550  8.860023  9.548298 26.848650 15.274161 36.238239  3.087070  5.457105 13.761177

我将把它作为练习留给读者添加第一个点和最后一个点之间的最后一个distance

我认为@Gregor Thomasdiff方法足够简洁。 如果您对计算距离的dist感兴趣,这是另一种选择。

> d <- rbind(df, df[1, ])

> with(d, diff(y) / diff(x))
 [1]  1.5365854  3.1948052  1.0583333  0.7464789 -1.0454545  1.1292135
 [7]  1.0186916  0.8581818 -0.4642857  0.2452830  0.7706422 -1.8039216

> (m <- as.matrix(dist(d)))[col(m) - row(m) == 1]
 [1]  7.516648 25.776928 17.472550  8.860023  9.548298 26.848650 15.274161
 [8] 36.238239  3.087070  5.457105 13.761177 10.519030

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM