我的数据结构如下:
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")
我希望从连续运动矢量的点积和角速度或角位移的变化率计算角位移。我使用了下面的代码,但这不会根据MovementAnalysis$Name
的变化重新开始分析?简单地说,我希望计算每个人MovementAnalysis$Sample
的角速度。
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
}
我想使用dplyr
来完成上述操作但不确定代码?我尝试过以下方法:
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))
这会返回错误Error: unexpected ')' in: " group_by(Name) %>% mutate(AngularV = function(x))"
有关问题的任何想法吗?前两行Name
的前两行Angular Velocity应为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`
答案 0 :(得分:1)
首先,不要使用逐元素乘法,然后使用sum:sum(a*b)
。使用矩阵乘法运算符:a %*% b
。那就是:(a %*% b) / (sqrt(a %*% a) * sqrt(b %*% b))
但你真的想要获得余弦距离,这是与Find cosine similarity between two arrays