Reputation: 25
My data.frame Calculations
is structured as follows:
head(Calculations)
Name x y Sample Time
1 Thomas 26.6627 -12.3782 1 0.01
2 Thomas 26.6564 -12.3711 2 0.02
3 Thomas 26.6497 -12.3635 3 0.03
4 Caitlin 28.6423 -14.3555 1 0.01
5 Caitlin 28.6353 -14.3472 2 0.02
6 Caitlin 28.6269 -14.3385 3 0.03
Whereby SampleRate <- 100
and k <- as.integer(SampleRate)
whilst m_velocity<- matrix(NA, length(Calculations$x))
I wish to run the following while loop to calculate velocity over time:
attach(Calculations)
i <- 2
while(i < length(x) - k){
m_velocity[i] <- sqrt(sum((x[i] - x[i-1]) ^2, (y[i] - y[i-1]) ^2)) / (1/SampleRate)
i <- i+1
}
However, this does not restart for each Name
. For example, the first velocity entry for Caitlin would be NA and not calculated from the X and Y coordinates from Thomas.
UPDATED I used the following code to obtain Velocity:
Calculations %>%
arrange(Name) %>%
group_by(Name) %>%
mutate(Velocity = sqrt( (x - lag(x) )^2 + (y - lag(y) )^2 ) * SampleRate)
but when I checked the first entry of Sample
for each Name
using ddply(Calculations,.(Name),function(x) head(x,1))
velocity is still being calculated from the previous person's X and Y coordinates. Any suggestions?
SOLVED
My issue was stemming from first loading dplyr
then plyr
which creates issues as stated here.
Upvotes: 1
Views: 144
Reputation: 4024
You can do this without a while loop.
library(dplyr)
calculations %>%
group_by(Name) %>%
mutate(velocity = sqrt( (x - lag(x) )^2 + (y - lag(y) )^2 ) * SampleRate)
Upvotes: 3