# Calculating average data of neighbour grids based on location and returning data to grid in QGIS

I have generated a grid layer from a vector layer in QGIS, and merged the point attribute into the grid layer by "joint by location".

I now need to:

1. calculate the average of some attributes for each of the nine adjacent grids (nine grids forming a square) (Figure 1)
2. return this value to the middle grid
3. need to do this for each grid in the grid layer

What should I do? I've been working on this for a long time but I can't figure it out.

Create a new field using field calculator with this expressions, replacing `value` (twice!) with the name of the field that contains the values you want to calculate the mean from. Be aware that `array_mean ()` is available since QGIS 3.18.

``````array_mean ( array_append( overlay_nearest( @layer,value, limit:=8), value))
``````

Screenshot: "value" attribute for each cell in black (input), mean of 9 neighboring cells in red (output) - the expression here is used together with a `round()` function to limit the result to 4 decimals:

• Thank you very much! I'll try it later. Two unrelated questions I'd like to ask first. 1. when running this kind of code, my QGIS is always very laggy and sometimes stuck, I don't know if it's a version problem or the amount of data is too large? 2. do you have any recommended reading material or tutorials for newbies who want to learn QGIS formulas and code? Once again, thank you very much! I really should have asked this question earlier. Jul 15, 2021 at 10:29
• Normally, it should run fast. But depending on the size of your grid, it could take a bit longer. If you have tens or hundred of thousends of grid cell, then of course it takes quite a while. For QGIS expressions, best see the documentation of the expressions: docs.qgis.org/3.16/en/docs/user_manual/working_with_vector/… or read the help in the expression editor. There are also some tutorial out there, e.g. by Ujaval Gandhi - search for his name + `QGIS expressions` Jul 15, 2021 at 10:41

You can create a virtual layer to find the adjacent cells and compute the mean

Go to the menu `Layer > Add Layer > Add/Edit Virtual Layer...` and enter the following query. Replace the layer name / field name for yours.

It will create a new dynamic layer that you can export to a Shapefile or else to persist it.

``````SELECT central.id, central.geometry, avg(neighbor.field_to_be_averaged) as mean_val
FROM my_polygon_layer central
JOIN my_polygon_layer neighbor
ON st_intersects(central.geometry, neighbor.geometry)
GROUP BY central.id
``````

You can add more fields as needed, or even use `central.*` instead of `central.id, central.geometry` to keep every fields.

• Why not using `ST_Touches()`? Jul 15, 2021 at 13:18
• @Taras for the central cell
– JGH
Jul 15, 2021 at 13:27