r - Finding total distance moved with for loop
问题描述
I'm trying to find the overall distance moved by a worker and my df
looks something like
Name x y
John 12 34
John 15 31
John 8 38
John 20 14
I've tried using the dist(rbind())
function, but the result given is not correct. It just gives the result of sqrt((row1)^2+(row2)^2+(row3)^2+(row4)^2)
, which I don't think is correct.
So I'm trying to use for
loop to do this, so that dist between row 1 and 2 , 2 and 3, and so on is calculated separately and summed up later. How would I do this?
My code currently looks like:
for(i in nrow(df)){
n <- dist(rbind(df$x,df$y))
}
and this just gives me the wrong single result mentioned above, and not a list of individual distances for each 1-2 row/s.
My expected output would be like:
4.2426
9.8995
26.8328
and I can sum them up later by I guess running:
sum(n)
right?
解决方案
使用基数 R,您可以dist
在每对连续的行上调用 ,然后调用cumsum
相邻距离以按名称获取结果。
df <- read.table(text="Name x y
John 12 34
John 15 31
John 8 38
John 20 14
Mark 11 13
Mark 16 18", header=TRUE)
by(df, df$Name, function(mat) {
idx <- seq_len(nrow(mat))
cumsum(mapply(function(i,j) dist(mat[c(i,j), c("x","y")]),
head(idx, -1), tail(idx, -1)))
})
或者,下面只计算整个距离矩阵并提取第一个非对角线
by(df, df$Name, function(mat) {
idx <- seq_len(nrow(mat))
cumsum(
as.matrix(dist(mat[,c("x","y")]))[cbind(head(idx, -1), tail(idx, -1))])
})
推荐阅读
- view - 在颤振上模态显示自定义视图
- r - 如何减少使用差分进化估计的收益率曲线的价格误差?
- informix - 如何在 Informix 数据库中创建用户并限制会话数
- angular - 根据条件动态加载不同的组件
- python - 如何抓取受密码保护的网站
- node.js - Nodemailor 无法跨域发送邮件
- java - 如何在 Java 1.6 中将 UTC 日期转换为本地日期
- angular - PrimeNG TurboTable 排序图标在启用默认排序的情况下不可见
- architecture - DAO 层应该如何实现?一张表 DAO 还是多表 DAO?
- vhdl - VHDL为信号名称分配一个数字