[GIS] Stats on individual grid points nearest neighbours

arcgis-desktopnearest neighborqgisr

I have shp of points where each point is the centroid of the individual cells of a 1*1km grid (~ 500 000 points). For each of these points, I have their coordinates and elevation.

What I want: for each of these points, I want to compute the mean, std dev, min, max and median elevation of the nearest 8 surrounding points.

What I did so far: I wrote an R script to identify each of the nearest points for each of the points of the grid. But considering the size of the dbf and the general slowness of R, it takes forever.

My tools: QGIS, ArcGIS, SAS, R or other free software if needed.

Does any one have a suggestion to do this (1- identify the direct neighbors, 2- compute summary stats from the elevation of these neighbors) in a more efficient way, using GIS?

Best Answer

There is the spdep R package, which has a K-nearest neighbor algorithm implemented. I am not sure if its more efficient than what you have, but it might be worth a try.

Here is an example script to show how you could calculate the values you wanted and put them into a data frame.

# Load spdep package
library(spdep)

# Load example data
# (replace this by loading your shapefile)
example(columbus)

# Extract coordinates from shape
coords <- coordinates(columbus)

# Use the area of the example data as a replacement for elevation
# (select column with elevation value from attribute table here)
area.vector <- columbus$AREA

# Calculate K nearest neighbors using spdep package
col.knn <- knearneigh(coords, k=8)

# Extract neighbor index matrix
neighbors <- col.knn$nn

# Prepare empty dataframe for calculations
output<-data.frame(area.vector, mean=NA, sd=NA, min=NA, max=NA, median=NA)

# Loop over neighbors matrix, calculate values
for(i in 1:nrow(columbus)){
    values <- area.vector[neighbors[i,]]
    output[i,2:6] <- c(mean(values), sd(values), min(values), max(values), median(values))
}

# View head of output to see if it worked
head(output)
Related Question