[R] Euclidean Distance in 3 Dimensions

Patzelt, Edward patzelt at g.harvard.edu
Wed Aug 20 22:12:58 CEST 2014


R Community -

I am attempting to write a function that will calculate the distance
between points in 3 dimensional space for unique regions (e.g. localized
brain regions such as the frontal lobe).

For example I'm looking to compare each point in region 45 to every other
region in 45 to establish if they are a distance of 8 or more apart. I can
do this linearly comparing each distance to the previous but this is not
comparing all points.

structure(list(Cluster.Index = c(46L, 46L, 46L, 46L, 46L, 45L,
45L, 45L, 45L, 45L, 44L, 44L, 44L, 44L, 44L, 43L, 43L, 43L, 43L,
43L), Value = c(8.21, 7.96, 7.85, 7.83, 7.8, 5.38, 4.56, 4.5,
4, 3.99, 5.42, 4.82, 4.21, 4.18, 3.91, 4.79, 4.27, 3.24, 3.06,
3.04), x = c(33L, 38L, 37L, 36L, 38L, 47L, 42L, 43L, 44L, 42L,
50L, 41L, 39L, 41L, 44L, 46L, 45L, 45L, 41L, 46L), y = c(15L,
12L, 12L, 13L, 13L, 91L, 84L, 84L, 95L, 96L, 69L, 70L, 65L, 65L,
59L, 41L, 40L, 46L, 44L, 47L), z = c(41L, 38L, 41L, 39L, 33L,
39L, 40L, 42L, 44L, 45L, 34L, 36L, 30L, 35L, 39L, 53L, 47L, 61L,
52L, 57L), X = c(NA, 6.557438524302, 3.16227766016838, 2.44948974278318,
6.32455532033676, 78.7464284904401, 8.66025403784439, 2.23606797749979,
11.2249721603218, 2.44948974278318, 30.2324329156619, 9.2736184954957,
8.06225774829855, 5.3851648071345, 7.81024967590665, 22.8910462845192,
6.16441400296898, 15.2315462117278, 10.0498756211209, 7.68114574786861
)), .Names = c("Cluster.Index", "Value", "x", "y", "z", "X"), row.names =
c(NA,
20L), class = "data.frame")

mainDat <- data.frame()
for(i in 2:nrow(dat)){
tempDist <- (sqrt((dat$x[i] - dat$x[i-1])^2 + (dat$y[i] - dat$y[i-1])^2 +
(dat$z[i] - dat$z[i-1])^2))
dat$X[i] <- c(tempDist)
if(dat$Cluster.Index[i] != dat$Cluster.Index[i-1]){
mainDat <- rbind(mainDat, dat[i,])
}
if((dat$Cluster.Index[i] == dat$Cluster.Index[i-1])) {
if(tempDist > 8){
mainDat <- rbind(mainDat, dat[i,])
}
}
}




-- 

*Edward H Patzelt | Clinical Science PhD StudentPsychology | Harvard
University *

	[[alternative HTML version deleted]]



More information about the R-help mailing list