Calculate Euclidean distance between points with rolling function in data.table

Viewed 350

I have a data.table with transects in different areas, coordinates x and y are projected as UTM 36S.

How can I calculate the (Euclidean) distance between consecutive points with data.table, per area, using a rolling function?

        x       y                date  area
1: 860030 9956743 2019-10-17 13:40:36 area1
2: 860025 9956762 2019-10-17 13:42:04 area1
3: 860025 9956764 2019-10-17 13:43:06 area1
4: 859984 9956795 2019-10-17 13:44:06 area1
5: 859928 9956803 2019-10-17 13:45:06 area1
6: 852010 9945485 2018-12-06 06:12:04 area2
7: 852024 9945476 2018-12-06 06:12:15 area2
8: 852033 9945470 2018-12-06 06:12:23 area2

dput x object:

structure(list(x = c(860030.089581219, 860024.678438056, 860024.669866417, 
859984.428586571, 859928.100890497, 852009.95451107, 852024.297711228, 
852033.150084026), y = c(9956743.22114593, 9956761.52220698, 
9956763.54512543, 9956795.19408176, 9956802.56503778, 9945485.12489829, 
9945475.70943483, 9945469.72972126), date = structure(c(1571319636, 
1571319724, 1571319786, 1571319846, 1571319906, 1544076724, 1544076735, 
1544076743), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    area = c("area1", "area1", "area1", "area1", "area1", "area2", 
    "area2", "area2")), row.names = c(NA, -8L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x558bcca1a3f0>, index = integer(0))
1 Answers

Here are two options:

1) using frollapply:

library(data.table)
setDT(DT)[, sqrt(Reduce(`+`, frollapply(.SD, 2L, function(v) diff(v)^2))), area, .SDcols=x:y]

Since frollapply applies FUN to each column separately, you can split the Euclidean distance calculations into 2 (for x and y) before summing and taking the square root.

2) using shift:

DT[, sqrt((x - shift(x))^2 + (y - shift(y))^2), area]

output:

[1]           NA    19.084269     2.022937    51.195869    56.807925 13812.367407    17.157457    10.682765
Related