简体   繁体   中英

Connect nearest neighbor point

I have a list of xy coordinates for 30 data points (green dots in the pic) and I would like to connect them together.

情节

How can I do it in R? At the moment, I computed the distance matrix between each point by dist() to obtain the closest neighbor for each point. However this result in 30 edge pairs... sometimes multiple edges connect to the same point which is not I want :( How can I solve this problem in R?

  cities_num=10
  cor.matrix=matrix(0,nrow=cities_num,ncol=2)
  for (r in 1:cities_num){
  cor.matrix[r,]=c(sample(1:500, 1),sample(1:500, 1))}
  par(mar=c(4,4,2,4))
  plot(cor.matrix,pch=4,xlab="X coordinate",ylab="Y coordinate")
  centroid.x=mean(cor.matrix[,1])
  centroid.y=mean(cor.matrix[,2])
  bead_num=cities_num+20
  t=seq(0,pi*2,length=bead_num) 
  coords=t(rbind( centroid.x+sin(t)*10, centroid.y+cos(t)*10))
  for (point in 1:bead_num){
    symbols(x=coords[,1][point],y=coords[,2][point],circles=0.5,
            inches = FALSE, add = TRUE)
  }

Not sure what a "symbol point" is and there seemed to be too many undefined objects in your code so I made my own set of "points". If just a regular point then use polygon :

 dat <- data.frame(s=sin(seq(pi,-pi,length=25)),
                    c=cos(seq(pi,-pi,length=25)) )
 png();
     plot(0,0, xlim=c(-1.5,1.5),ylim=c(-1.5,1.5) );
       with(dat, points(s,c));
       with(dat, polygon(s,c) ) 
 dev.off()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM