Calculating all distances between one point and a group of points efficiently in R

后端 未结 5 624
太阳男子
太阳男子 2020-12-15 09:55

First of all, I am new to R (I started yesterday).

I have two groups of points, data and centers, the first one of size n and

5条回答
  •  孤城傲影
    2020-12-15 10:41

    You may want to have a look into the apply functions.

    For instance, this code

    for (j in 1:K)
        {
        d[j] <- sqrt(sum((centers[j,] - data[i,])^2))
        }
    

    Can easily be substituted by something like

    dt <- data[i,]
    d <- apply(centers, 1, function(x){ sqrt(sum(x-dt)^2)})
    

    You can definitely optimise it more but you get the point I hope

提交回复
热议问题