Skip to content
Prev 156060 / 398513 Next

Join data by minimum distance

Hi,

First of all thanks to everybody who came with suggestions and solutions, but Simon came with perfect code ;-)

We work with data that usually is projected in locat UTM coordinates, so i've changed the code as following and it works like a charm:

## code begins
## Euclidian distance 
##this has advantage that i can use a z coordinate if i have it and change the dist function accordingly

dist <- function(x1, y1, x2, y2) {
((x1-x2)^2 + (y1-y2)^2)^0.5
}

dist.merge <- function(x, y, xeast, xnorth, yeast, ynorth){
tmp <- t(apply(x[,c(xeast, xnorth)], 1, function(x, y){
dists <- apply(y, 1, function(x, y) dist(x[2],
x[1], y[2], y[1]), x)
cbind(1:nrow(y), dists)[dists == min(dists),,drop=F][1,]
}
, y[,c(yeast, ynorth)]))
tmp <- cbind(x, min.dist=tmp[,2], y[tmp[,1],-match(c(yeast,
ynorth), names(y))])
row.names(tmp) <- NULL
tmp
}
 

## code ends

#demo

track <- data.frame(xt=runif(10,0,360), yt=rnorm(10,-90, 90))
classif <- data.frame(xc=runif(10,0,360), yc=rnorm(10,-90, 90), v1=letters[1:20], v2=1:20)
dist.merge(track, classif, 'xt', 'yt', 'xc', 'yc')

Again,

Thanks for all the help,
Monica
_________________________________________________________________

 Live.