Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...