0

I have spatiotemporal movement data (event data from a mobile network with over 8000 users) in a .csv with four columns (date/time, ID, lat, long). How would I calculate speed travelled between coordinates?

Co-ord format is (11.559257, 48.093384) etc.

Any advice at all would be much appreciated!

  • 1
    See the answers to [This question](https://stackoverflow.com/q/31668163/4752675) to get the distance between two points expressed as lat-lon. Then `speed = distance/time` – G5W Apr 17 '18 at 20:55

1 Answers1

0

Try something like this...

library(geosphere)
library(sp)

num_records = 6
time_max = 60*60*24*10

df <- data.frame(     
  date_time = sort(as.POSIXct(runif(num_records, min=0, max=time_max), origin="2010-01-01")),
  ID = c("Honolulu", "Kapolei", "Sarajevo", "Krupac", "South Pole", "North Pole"),
  lat = c(18.41, 18.35, 21.31, 21.33, -90, 90),
  long = c(43.86, 43.78, -157.86, -158.06, 1, 1)
)

sp_points <- SpatialPoints(df[c('long', 'lat')], proj4string=CRS("+proj=longlat"))

travel_mat <- data.frame(
  from = 1:(num_records - 1),
  to = 2:num_records
)

travel_mat$elapsed_time <- as.numeric(df$date_time[travel_mat$to] - df$date_time[travel_mat$from], units = "hours")
travel_mat$distance <- mapply(
  function(from, to) distm(sp_points[from], sp_points[to], fun=distVincentyEllipsoid)[1],
  from = travel_mat$from,
  to = travel_mat$to
)

# units are in meters and minutes, adjusting to kilometers per hour
travel_mat$speed_kph <- round(travel_mat$distance / travel_mat$elapsed_time / 1000, 2)
travel_mat$text <- paste(df$ID[travel_mat$from], "-", df$ID[travel_mat$to])

so if your input csv looked like this:

df
            date_time         ID    lat    long
1 2010-01-01 10:43:54   Honolulu  18.41   43.86
2 2010-01-05 01:09:28    Kapolei  18.35   43.78
3 2010-01-06 06:41:24   Sarajevo  21.31 -157.86
4 2010-01-07 09:31:51     Krupac  21.33 -158.06
5 2010-01-10 06:54:45 South Pole -90.00    1.00
6 2010-01-10 22:10:00 North Pole  90.00    1.00

your output data frame should look like this:

travel_mat
 from to elapsed_time    distance speed_kph                    text
    1  2     86.42614    10750.59      0.12      Honolulu - Kapolei
    2  3     29.53233 15029818.36    508.93      Kapolei - Sarajevo
    3  4     26.84083    20867.27      0.78       Sarajevo - Krupac
    4  5     69.38162 12361579.93    178.17     Krupac - South Pole
    5  6     15.25400 20003931.46   1311.39 South Pole - North Pole
J. Win.
  • 6,662
  • 7
  • 34
  • 52