I have a sample of points villages x,i, and I want to know the distance between each village x,i and the nearest village x,j. The i, and j depicts two different samples. I am able to find the distance but in addition to the distance I would like to get the name of the nearest village j for each village i. Name is the first column village_j$name.

village_i <- readOGR(~path/village_i)
coordinates village_i <- c('x1', 'x2')
proj4string(village_i) <- CRS("+init=epsg:4326")
village_i = spTransform(village_i, CRS("+init=epsg:4326"))

village_j <- readOGR(~path/village_j)
coordinates village_j <- c('x1', 'x2')
proj4string(village_j) <- CRS("+init=epsg:4326")
village_j = spTransform(village_j, CRS("+init=epsg:4326"))

g1=get.knnx(coordinates(village_j), coordinates(village_i), k=1)
g1 <- data.frame(g1)
colnames(g1)[1] <- "village_j"
g1$ID <- seq.int(nrow(g1))
pixels <- merge(village_i,g1,by="ID")
remove(g1, village_j)
names(village_i)[names(village_i) == "nn.dist"] <- "dist_village_j"

Any idea?

  • Take a look at theknn function in the spatialEco package. – Jeffrey Evans Dec 1 '19 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.