My data is structure as follows:
dput(head(MovementAnalysis,10))
structure(list(Name = c("Amber", "Amber", "Amber", "Amber", "Amber",
"Jeff", "Jeff", "Jeff", "Jeff", "Jeff"), Sample = c(1, 2, 3, 4, 5, 1, 2,
3, 4, 5), X = c(26.66, 26.66, 26.65, 26.64, 26.64, 26.47, 26.46, 26.45,
26.43, 26.42), Y = c(-12.38, -12.37, -12.36, -12.36, -12.35, -12.23,
-12.22, -12.22, -12.22, -12.22)), .Names = c("Name", "Sample", "X", "Y"), row.names = c(NA, 10L), class = "data.frame")
I wish to calculate angular displacement, from the dot product of consecutive movement vectors, and angular velocity or the rate of change in angular displacement. I have used the code below but this does not restart the analysis according to a change in MovementAnalysis$Name
? Simply, I wish to calculate angular velocity across MovementAnalysis$Sample
for each person.
i <- 1
sampleRate <- 2
k <- as.integer(sampleRate)
a_velocity <- matrix(NA, length(MovementAnalysis$X))
if (i > k)
{
a <- c(x[i] - x[i-k], y[i] - y[i-k])
b <- c(x[i+k] - x[i], y[i+k] - y[i])
a_velocity[i] <- acos(sum(a * b) / (sqrt(sum(a * a)) * sqrt(sum(b * b)))) * (180 / pi)
}
i <- i+1
}
I would like to use dplyr
to complete the above but am unsure of the code? I have tried the following:
function(x) {
i <- 2
while(i < length(X) - k) {
if (i > k) {
a <- c(X[i] - X[i-k], Y[i] - Y[i-k])
b <- c(X[i+k] - X[i], Y[i+k] - Y[i])
AngularVelocity = acos(sum(a * b) / (sqrt(sum(a * a)) * sqrt(sum(b * b)))) * (180 / pi)
}
i <- i+1
}
}
MovementAnalysis <- MovementAnalysis %>%
arrange(Name) %>%
group_by(Name) %>%
mutate(AngularV = function(x))
This returns an error of Error: unexpected ')' in: " group_by(Name) %>% mutate(AngularV = function(x))"
Any ideas on the problem? The first 2 rows of Angular Velocity, for the first two rows of Name
should be NA
.
SessionInfo()
R version 3.1.2 (2014-10-31)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252
LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C LC_TIME=English_Australia.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.3.0.2 plyr_1.8.1 ggplot2_1.0.0
loaded via a namespace (and not attached):
[1] assertthat_0.1 colorspace_1.2-4 DBI_0.3.1 digest_0.6.4
grid_3.1.2 gtable_0.1.2
[7] labeling_0.3 lazyeval_0.1.9 magrittr_1.0.1 MASS_7.3-35
munsell_0.4.2 parallel_3.1.2
[13] proto_0.3-10 Rcpp_0.11.1 reshape2_1.4 scales_0.2.4
stringr_0.6.2 tools_3.1.2`