简体   繁体   中英

calculating the distance from center to each data points

Hi I want to calculate the distance from center to each data points I have used the following codes but it's not working, df is my dataframe and c1 is center Thanks in advance

        dist <- NULL
    for(i in 1:nrow(df)) dist[i] <- euc.dist(df[i,],c1[i,])
        dist

And my solution as well:

Let data be matrix m:

     x y
[1,] 2 3
[2,] 5 6
[3,] 3 2
[4,] 5 1
[5,] 4 1
[6,] 6 8

Then centers are given by:

cnt = c(mean(m[,1]),mean(m[,2]))

So the code returning vector of distance between every row of m and cnt will be:

apply(m,1,function(x,cnt) {(sqrt((x[1] - cnt[1])^2+(x[2]-cnt[2])^2))},cnt)

And the result is:

[1] 2.223611 2.635231 1.900292 2.635231 2.505549 4.859127

You have 2 ways to deal with the problem: calculating all distances between points in df, or just with a center.

First approach (not efficient, you calculate all distances and get only a little subset):

set.seed(123)
mydf <- data.frame(x=runif(10), y=runif(10))
c1 = c(x=3, y=4)
mydf <- rbind(c1,mydf)
as.matrix(dist(mydf))[-1,1] #exclude distance from the center to itself

And the second:

c1 = c(x=3, y=4)
euc.dist <- function(x1) sqrt(sum((x1 - c1) ^ 2))
set.seed(123)
mydf <- data.frame(x=runif(10), y=runif(10))
apply(mydf, 1, euc.dist)

Results are the same:

4.076530 4.179765 4.213305 4.028456 4.407819 4.282502 4.494677 4.484104 4.413574 3.967853

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM