Achal Neupane
Achal Neupane

Reputation: 5719

How can I calculate distance of points in multi-dimension space from the centroid

I have centroid of space in 5 dimenions given as centroid<-c(-0.0160560385542169, -0.0125691807228916, -0.000605079518072289, -0.00174781445783133, -0.0199511518072289). I also have a matrix with 5 samples where PCA1:PCA5 represent 5 dimensions of points for those samples. How can I calculate the euclidean distance for each of these samples from the centroid? If it was the distance from one point to another, I could have simply done dist(mymat[,-1]), but I am not sure how I can get the distance from the centroid. Can someone please suggest?

mymat<- structure(c("10687:G41F", "10687:SKDP-225.3", "10687:2671", "10687:LPH-001-16_SCC", 
"10687:MC1R-694CB-T", "-0.0039950", "-0.0203415", "-0.0200395", 
"-0.0147320", "-0.0196970", "-0.0140180", "-0.0181240", "-0.0165090", 
"-0.0148700", "-0.0170765", "-0.0136615", "-0.0010915", "-0.0014500", 
" 0.0020240", "-0.0021095", "-0.0002395", "-0.0019710", "-0.0017595", 
" 0.0036180", "-0.0036255", "-0.0184015", "-0.0197400", "-0.0238185", 
"-0.0282375", "-0.0323130"), .Dim = 5:6, .Dimnames = list(c("1", 
"2", "3", "4", "5"), c("samples", "PCA1", "PCA2", "PCA3", 
"PCA4", "PCA5")))

Upvotes: 0

Views: 777

Answers (1)

Chris
Chris

Reputation: 1615

dist should generalize to however many dimensions you want...

centroid <- c(-0.0160560385542169, -0.0125691807228916, -0.000605079518072289, 
 -0.00174781445783133, -0.0199511518072289)
rbind(c("centroid", centroid), mymat) -> k
dist(k, "euclidean") -> dd
as.matrix(dd) -> dd
k[,1] -> rownames(dd) 
as.data.frame(dd)
dd[2:6,1] -> dist_to_centroid
View(as.data.frame(dist_to_centroid))

Upvotes: 2

Related Questions