'How can I find the distance between consecutive coordinates in R?

I have a dataframe similar in structure to the one created below:

id <- rep(c("a", "b", "c", "d"), each = 3)
date <- seq(as.Date("2019-01-30"), as.Date("2019-02-10"), by="days")
lon <- c(-87.1234, -86.54980, -86.234059, -87.2568, -87.65468, -86.54980, -86.234059, -86.16486, -87.156546, -86.234059, -86.16486, -87.156546)
lat <- c(26.458, 26.156, 25.468, 25.157, 24.154, 24.689, 25.575, 25.468, 25.157, 24.154, 26.789, 26.456)
data <- data.frame(id, date, lon, lat)
data <- data %>% arrange(id, date)

I would like to measure the distance between consecutive points grouped by id. I do not want a distance matrix, which is why I refrain from using raster::pointDistance. I tried separating each unique id into its own sf dataframe (in reality I have ~400 ids so I kind of have to separate for the actual calculation due to the size) and using the following code:

#put rows for each id in their own dataframes
un1 <- unique(data$id)
for(i in seq_along(un1)) 
  assign(paste0('id', i), subset(data, id == un1[i]))
#create point distance function
pt.dist <- function(dat){dat$pt.dist <- st_distance(dat, by_element=TRUE)
  return(dat)}
#run function across every dataframe in working environment
e <- .GlobalEnv
nms <- ls(pattern = "id", envir = e)
for(nm in nms) e[[nm]] <- pt.dist(e[[nm]])

When I run this, all I get is a geometry column with lon and lat listed in a pair. I have also tried segclust2d::calc_distance like below:

distance <- function(dat){calc_dist(dat, coord.names = c("lon", "lat"), smoothed = FALSE)}
for(nm in nms) e[[nm]] <- distance(e[[nm]])

which returns a column where the distances are all 0 meters.

Any help would be greatly appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source