我要计算两个向量的斜率和距离。我使用以下代码
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")从斜率的输出中可以看到,有11个值正在出现。我也想要12-1的坡度。我怎么能拿到呢?我只想要1-2,2-3,3-4,4-5,5-6,6-7,7-8,8-9,9-10,10-11,11-12和12-1组合的值。我怎样才能做到这一点?预期输出是
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发布于 2021-11-30 14:11:05
我认为diff approach by @Gregor Thomas足够简洁。这是另一个选项,以防您对计算diatances的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发布于 2021-11-30 13:59:56
没有很好的diff函数来获取最后一个和第一个向量元素的差异,您可以直接使用(y[12] - y[1]) / (x[12] - x[1]),或者如果您想要更一般地使用tail(x, 1)表示最后一个元素,使用head(x, 1)表示第一个元素。直接计算并将其附加到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。
https://stackoverflow.com/questions/70170478
复制相似问题