Separate x, y, to calculate distance between points, using euclidean function
Assign x to first, third, firth, etc element values from moves
vector. Assign y to second, fourth, sixth, etc element values from moves
vector.
The sequence should assign two adjacent elements, then move to the next two adjacent element, no overlaps, simply moving forward in the vector for assignments.
Final pairs should be [x=3 y=5],[x=7 y=11], [x=13 y=17] [x=19 y=23], [x=29 y=31], [x=37 y=41], [x=43 y=47], [x=53 y=59], [x=61 y=67], [x=71 y=73], [x=79 y=83], [x=89 y=97].
For each pairwise elements, x, y, the calculated euclidean distance should append() and store the results in a vector e.g., 'vector_of_pairs_distance'
euclidean <- function(x, y) sqrt(sum((x - y)^2))
vector_of_pairs_destinces = (NULL)
pair = 0
for (j in moves) {
pair =+ 2
x <- moves[j]
y <- moves[j+1]
append(vector_of_pairs_distance, euclidean(x,y))
j=+1
if (pair > 18) {break}
}
[x=3 y=5],[x=7 y=11], [x=13 y=17] [x=19 y=23], [x=29 y=31], [x=37 y=41], [x=43 y=47], [x=53 y=59], [x=61 y=67], [x=71 y=73], [x=79 y=83], [x=89 y=97]
moves
[1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
I think your goal is to get the Euclidean distance of each point to the following point? If so, you can do the following:
euclidean <- function(x1, y1, x2, y2) {
sqrt((x2 - x1)^2 + (y2 - y1)^2)
}
# change `moves` vector to matrix with x, y pairs in each row
moves <- matrix(moves, ncol = 2, byrow = TRUE)
# pass lagged points to `euclidean()` to get sequential distances
euclidean(
x1 = moves[-nrow(moves), 1],
y1 = moves[-nrow(moves), 2],
x2 = moves[-1, 1],
y2 = moves[-1, 2]
)
# [1] 7.211103 8.485281 8.485281 12.806248 12.806248 8.485281 15.620499
# [8] 11.313708 11.661904 12.806248 17.204651
Or, using stats::dist()
:
# change `moves` to matrix as above
moves <- matrix(moves, ncol = 2, byrow = TRUE)
# compute matrix of Euclidean distances
move_dists <- as.matrix(dist(moves))
# get distance from each pair to the next by extracting first sub-diagonal
move_dists[row(move_dists) == col(move_dists) + 1]
# [1] 7.211103 8.485281 8.485281 12.806248 12.806248 8.485281 15.620499
# [8] 11.313708 11.661904 12.806248 17.204651
(Note, the first element of your vector, 2
, wasn’t included in your lists of pairs; I assumed this was an error and removed the 2
.)