Using the sqrt function on a data frame

I want to calculate the following equation between two points, I don't know how to apply this across the entire dataset:

Point  x y z
1      4 3 8
2      8 5 4
3      5 4 7
4      2 7 4

D1,2 = sqrt((x2-x1)²+ (y2-y1)²+( z2-z1)²)

      

+3


source to share


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







All Articles