Home > front end >  How to calculate slope and distance of two vectors in r?
How to calculate slope and distance of two vectors in r?

Time:12-01

I want to calculate slope and distance of two vectors. I am using the following code

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")

You can see in the output of slope that 11 values are coming. I want to have the slope of 12-1 also. How can I get that? and the from distance output I only want the values of 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-9, 9-10, 10-11, 11-12 and 12-1 combinations. How can I achieve it? The expected output is

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

CodePudding user response:

I think the diff approach by @Gregor Thomas is concise enough. Here is another option in case you are interested in dist for computing diatances.

> 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

CodePudding user response:

There's no nice diff function for getting the difference of the last and first vector elements, you can directly use (y[12] - y[1]) / (x[12] - x[1]), or if you want to be more general use tail(x, 1) for the last element and head(x, 1) for the first element. Calculate it directly and append it to your slope vector.

For euclidean distance, of successive points, its most direct to calculate it directly: 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

I'll leave it as an exercise for the reader to add the last distance between the first and last points.

  • Related