I have telemetry data with a large number of detections for each individual (ID) at several stations. I want to calculate the total distance travelled by each ID in my study.
Each station is associated with its coordinates (Longitude and Latitude), which I convert to UTM data.
I have created a data that looks like mine, with the same data type (data_detections).
#generate a random data
generate_random_datetime <- function(start_date, end_date, n) {
seq(start_date, end_date, by = "min")[sample(1:(as.integer(difftime(end_date, start_date, units = "mins")) + 1), n)]
}
set.seed(123)
n <- 100
data_detections <- data.frame(
Date.and.Time..UTC. = generate_random_datetime(ymd_hms("2024-01-01 00:00:00"), ymd_hms("2024-01-20 23:59:59"), n),
Receiver = sample(1:10, n, replace = TRUE),
Latitude = runif(n, 52.0, 53.0),
Longitude = runif(n, 3.0, 4.0) ,
ID = as.character(sample(1:10, n, replace = TRUE))
)
I wanted to know if I could calculate my total distances like that, and if my distance unit was in meters.
#convert to UTM
coord <- SpatialPoints(data_detections[, c("Longitude", "Latitude")],
proj4string = CRS("+proj=longlat +datum=WGS84"))
coord.t <- spTransform(coord, CRS("+proj=utm +datum=WGS84 +zone=43"))
data_detections[, c("Longitude_UTM", "Latitude_UTM")] <- coordinates(coord.t)
head(data_detections)
#caclulate the total distance
total_distance <- function(data) {
coords <- as.matrix(data[, c("Longitude_UTM", "Latitude_UTM")])
distances <- sqrt(rowSums((coords[-1, ] - coords[-nrow(coords), ])^2))
distance <- sum(distances, na.rm = TRUE)
return(data.frame(distance = distance))
}
total_distances <- data_detections %>%
group_by(ID) %>%
group_modify(~ total_distance(.x))
print(total_distances)