Adaptation of nearest neighbour R code to identify locations of ponds within 1 km for each pond -


i have csv file pond areas , latitude , longitude coordinates 17,305 ponds. each pond identify coordinates of ponds within 1 km of it. r novice thought adapt nearest neighbour code. found loop in r book crawley:

x<-runif(100) y<-runif(100)  par(pty="s") plot(x,y,pch=16)  distance<-function(x1, y1, x2, y2) sqrt((x2 − x1)^2 + (y2 − y1)^2)  r<-numeric(100) nn<-numeric(100) d<-numeric(100) (i in 1:100) { (k in 1:100) d[k]<-distance(x[i],y[i],x[k],y[k]) r[i]<-min(d[-i]) nn[i]<-which(d==min(d[-i])) }     (i in 1:100) lines(c(x[i],x[nn[i]]),c(y[i],y[nn[i]])) 

i adapted , used deg.dist function in fossil uses haversine formula instead of using pythagoras.

install.packages("fossil") library(fossil)  pond_a<-read.csv("c:\\ pondarea_data\\pond_areas.csv")  r<-numeric(17305) nn<-numeric(17305) d<-numeric(17305) (i in 1:17305){ (k in 1:17305) d[k]<-with(pond_a,deg.dist(longitude[i],latitude[i],longitude[k],latitude[k]))   r[i]<-min(d[-i])   nn<-which(d<=1) } 

this appears give me identities of ponds in 1 km of last pond. try might have not been able work out how answer ponds. grateful if give me solution , perhaps explain why works.

thanks,

aidan

you can create boolean matrix using gwithindistance in rgeos package. row/col values represent rownames of sp object. can coerce matrix dataframe , assign sp object. example use meuse data sp package.

require(sp) require(rgeos) data(meuse)   coordinates(meuse) <- ~x+y  # create boolean matrix true distance condition |nnd <= d| true else false d=200 distmat <- gwithindistance(meuse, meuse, dist=d, byid=true)    # turn self-evaluation values na  diag(distmat) <- na  # join data cids <- colnames(distmat)   distmat <- as.data.frame(distmat)     names(distmat) <- paste("nid", cids, sep=".")       meuse@data <- data.frame(meuse@data, distmat)          str(meuse@data) 

Comments

Popular posts from this blog

design - Custom Styling Qt Quick Controls -

Unable to remove the www from url on https using .htaccess -