R句法糖 - 矢量距离

时间:2014-08-24 18:28:48

标签: r vector distance syntactic-sugar

我是R lang的新手,我认为可能有一种更简单的方法可以在目标矢量中获得最接近的矢量。

# Toy data
mydata = matrix(rpois(100, lambda=10), 10, 10)
candidate = rpois(10, lambda=10)

# Append a new row and calculate Euclidean distance
dist.to.proto = dist(rbind(mydata, candidate))
# Get the latest row
x = tail(as.matrix(dist.to.proto,), 1)
# From all the distances get the minimum, exclude the distance with itself.
proto = which.min(x[x > 0])

closest.vector = mydata[proto,]

1 个答案:

答案 0 :(得分:0)

  

您可以避免计算所有成对距离:

     

sqrt(rowSums(t(t(mydata) - 候选者)^ 2))