Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...