lundi 11 octobre 2021

How to mutate a new variable that summarizes X number of previous rows based on an if_else statement?

I have a spatial data frame with GPS points every second as well as the distance traveled between points and turning angles. I'd like to create a new column that summarises the amount of time it took to travel 10m and the average turning angle over the last 10 meters.

row x y date dx dy dist dt R2n abs.angle rel.angle
1 580988. 12981141. 2021-07-18 07:00:07 -1.99 -0.0128 1.99 1 0 -3.14 NA
2 580986. 12981141. 2021-07-18 07:00:08 0 0 0 1 3.94 NA NA
3 580986. 12981141. 2021-07-18 07:00:09 2.97 1.13 3.18 1 3.94 0.363 -2.79
4 580989. 12981142. 2021-07-18 07:00:10 0 0 0 1 2.21 NA NA

In other words, I'd like a column "sum.dist" that should always be close to 10 and then two more columns "sum.dt" and average.rel.angle that summarize the time it took the subject to move the previous 10 meters and the average rel.angle over those last 10 meters. I'm aware I'm probably going to need some kind of loop to check to see when the sum of distances is approximately 10 (say the first value to be greater than 10 meters?) and then count the number of rows and use that number of rows to summarize over row n and rows n-x. Unfortunately, I'm having a really hard time even figuring out how to start here. I'm comfortable with basic dplyr functions like mutate and summarise but I am inexperienced with loops.

Aucun commentaire:

Enregistrer un commentaire