Frage

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

War es hilfreich?

Lösung

I would use the dist function in the stats package. You can apply it to your data easily enough:

lapply( dfs , function(x) dist( x[,c("X","Y")] , diag = TRUE )[1:nrow(x)] )

The idea being that we operate on each dataframe, applying the dist function to the "X" and "Y" columns of each data frame. The subsetting at the end ( [1:nrow(x)] )is used to return only the distances between the first point and all the other points. Remove this subsetting if you want a full distance matrix for each track.

Andere Tipps

A possible solution :

f <- function(x) {
j <- nrow(x)
end <- as.numeric(x[j,c("X","Y")])
x <- x[-j,c("X", "Y")]
dist <- colSums((t(x)-end)^2)
dist
}
lapply(dfs, f)

Is it possible to calculate Euclidean distance directly in the function?

E.g. with this function am trying to calculate distance up to 8 m between observations, but I want to add a condition of only calculating distances between observations from the same group? My observations are trees with x,y position coordinates from different plots (11 plots, 2000 trees).

`search_dfixed <- function(id, x, y, dist) {
.class <- if (class(id) == "factor") {
"character"
 } else {
 class(id)
 }

 m <- as.matrix (dist(data.frame(x, y)))

 rownames(m) <- id; colnames(m) <- id

 z <- as.data.frame(m) %>%
 tibble::as_tibble() %>%
 dplyr::mutate(id = id) %>%
 tidyr::gather(competitor, .dist, -id) %>%
 dplyr::filter(
  .dist != 0,
  .dist <= dist
  ) %>%
  dplyr::arrange(id, .dist) %>%
  dplyr::mutate(
  id = 'class<-'(id, .class),
  competitor = 'class<-'(competitor, .class)
  )

  return(z)
  }`
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top