Nearest neighbor Analysis in QGIS



GIS is very useful in analyzing spatial relationship between features.It is important at times to find the features nearest to a feature in GIS.To achieve this, we can use the Distance Matrix that helps in calculating the distances between each point in the dataset.

Steps

You can use Vector > Analysis Tools > Distance Matrix, and a join to have an output layer that has all the required attributes.
I will use the Towns layer to exemplify. This will help in showing the distances and is quite small for faster processing.
1. Create a distance matrix using your layer as both destination and target.
Don't forget to tick "Use only the nearest (k) target points" and set it to 1.

Distance Matrix window
2. Open the CSV with add delimited text layer
Choose "Comma" as a delimiter, and set the geometry definition as no Geometry

Loading a Comma Delimited layer
3. Create a join in the original layer with the newly created table
 
Adding a join between two layers
4. Use Field calculator to populate a field with the desired values
Because of the join, we now have access to the distance table values from within the towns table of attributes, therefore it quite fairly easy to create a new field and populate it with our desired values.
Populating fields with values
5. Grouping the generated town data.
 We can now group the towns depending on the distances between them. To do that, we write a function to classify the data.

Classifying data in columns
That was a brief task that is very useful when conducting GIS analysis.
Happy hacking....