0

I want to calculated to which cluster a point belongs, based on the euclidean distance.

clusters    xcor       ycor
1           64.99206   78.48413
2           1102.00000 2466.67500
3           1598.11060 1298.10138
4           499.86441  736.72881

Location's are :

location   xcor   ycor
1          511    78
2          1354   2466
3          511    1298

So it should check for all the locations, to which cluster it belongs based on the shortest distance. Is there a function/package for this that can easily preform this?

Jelmer
  • 351
  • 1
  • 15

1 Answers1

0

Here's a solution using apply() and which.min():

apply(locs,1L,function(x) which.min(sqrt((x['xcor']-clus$xcor)^2+(x['ycor']-clus$ycor)^2)));
## [1] 1 2 4

Data

locs <- data.frame(location=c(1L,2L,3L),xcor=c(511L,1354L,511L),ycor=c(78L,2466L,1298L));
clus <- data.frame(clusters=c(1L,2L,3L,4L),xcor=c(64.99206,1102,1598.1106,499.86441),ycor=c(
78.48413,2466.675,1298.10138,736.72881));
bgoldst
  • 34,190
  • 6
  • 38
  • 64