Since you have velocity measured at constant time intervals, which you can sum over to get the total euclidean distance moved, you can actually just use the base
R function aggregate
to sum the V
data by each track identifier A
, which is what the command below does:
aggregate( V ~ A , data = t1 , sum , na.rm = TRUE )
Basically this says, aggregate
V for each value of A. The aggregation function is sum
(you can imagine this could easily be the mean
velocity for each track by using mean
instead of sum). We pass an additional argument to sum
which is na.rm
, telling it to ignore NAs in the data (which I assume are at t = 0
for each track).
Calculating 'as the crow flies' distance between first and last position by track:
For this we can split
the dataframe into sub-dataframes by the track identifier A
and then operate on each subset of the data, using lapply
to apply a simple hypotenuse calculation to the first and last row of each sub-dataframe.
## Split the data
dfs <- split(t1,t1$A)
## Find hypotenuse between first and last rows for each A
lapply( dfs , function(x){
j <- nrow(x)
str <- x[1,c("X","Y")]
end <- x[j,c("X","Y")]
dist <- sqrt( sum( (end - str)^2 ) )
return( dist )
} )