首页 > 解决方案 > 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

解决方案


使用基数 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))])
})

推荐阅读