Skip to content

Instantly share code, notes, and snippets.

@JoGall
Last active October 1, 2017 17:45
Show Gist options
  • Save JoGall/a34a1430590a17655a36a7a2d467ff1c to your computer and use it in GitHub Desktop.
Save JoGall/a34a1430590a17655a36a7a2d467ff1c to your computer and use it in GitHub Desktop.
Extract speed and direction from x,y-coordinates
# dataframe 'dat' w/ x,y-coords in columns 'x' and 'y' and timestamp in column, 'ts', e.g.:
library(soccermatics)
attach(tromso)
dat <- subset(tromso, id == 8)[,c(1,3:4)]
#calculate direction of each vector angle (in radians)
v <- diff(complex(real = dat$x, imaginary = dat$y))
dat$direction <- c(NA, diff(Arg(v)) %% (2*pi), NA) - pi
# calculate speed (distance / time interval)
dist <- c(NA, Mod(v))
dat$speed <- abs(dist / c(NA, difftime(dat$ts[-nrow(dat)], dat$ts[-1])))
# example plot
soccerFlow(dat, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment