I have asked about and receive great help for computing Euclidean distance in R before. Now, I need to compute the Euclidean distance from the first point relative to all the other points within the track data. Here is how my data looks like:
dput(head(t1))
structure(list(A = c(0L, 0L, 0L, 0L, 0L, 0L), T = 0:5, X = c(668L,
668L, 668L, 668L, 668L, 668L), Y = c(259L, 259L, 259L, 259L,
259L, 259L), V = c(NA, 0, 0, 0, 0, 0)), .Names = c("A", "T",
"X", "Y", "V"), row.names = c(NA, 6L), class = "data.frame")
And SimonO101 was so great in giving me a code that will compute the Euclidean distance from the starting position to the final position for each track:
## Split the data
dfs <- split(t1,t1$A)
## Find hypotenuse between first and last rows for each A
lapply( dfs , function(x){
j <- nrow(x)
str <- x[1,c("X","Y")]
end <- x[j,c("X","Y")]
dist <- sqrt( sum( (end - str)^2 ) )
return( dist )
} )
How do I edit the code, so that it will not just have the Euclidean distance from start to end, but from every X,Y position? Thanks again!
EDIT: And also: How to visualize the results as a matrix. Thank you
dist(mymatrix)should be all you need. - Carl Witthoftlapply( dfs , function(x) dist( x[,3:4] , diag = TRUE ) )you don't really needdiag = TRUE, but it helps to see thatdistcalculates zero distance between a point and itself! - Simon O'Hanlonresults <- lapply(....Note, that it will give you a list of matrices, one matrix for each unique track. To access a specific one use the[[operator, i.e. if you assign the output to a variable called results, thenresults[[1]]will give you the distance matrix for the first track. - Simon O'Hanlon