calculate the euclidean distance between multiple vectors in r

Adapting this answer to your data:

y$dist_from_x = t(outer(
  1:nrow(x),
  1:nrow(y),
  FUN = Vectorize(function(xi,yi) dist(rbind(x[xi,],y[yi,])))
))

y
#     Feature I  Feature II Feature III  Feature IV   Feature V dist_from_x
# 1 0.044428063 0.048164651 0.045638062 0.036595442 0.038433109    1.840726
# 2 0.003263986 0.005097862 0.004229567 0.004229749 0.003626148    1.926465
# 3 0.021800069 0.027690277 0.034727373 0.032815112 0.026041496    1.871883

Since x has one row, this would be a little more efficient:

# reset definition of y (or remove the dist_from_x column)
x_expanded = x[rep(1, nrow(y)), ]
y$dist_from_x = sqrt(rowSums((x_expanded - y)^2))
# same result as above

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top