Using the sqrt function on a data frame
1 answer
Best used dist
to calculate distance as pointed out in the comments.
data.frame(as.matrix(dist(df[,-1], diag = TRUE, upper = TRUE)))
You can also use sapply
to calculate distance (or apply some other formula) yourself
sapply(1:NROW(df), function(i)
sapply(1:NROW(df), function(j)
sqrt(diff(df$x[c(i,j)])^2 + diff(df$y[c(i,j)])^2 + diff(df$z[c(i,j)])^2)))
# [,1] [,2] [,3] [,4]
#[1,] 0.000000 6.000000 1.732051 6.000000
#[2,] 6.000000 0.000000 4.358899 6.324555
#[3,] 1.732051 4.358899 0.000000 5.196152
#[4,] 6.000000 6.324555 5.196152 0.000000
0
source to share