Say I have one layer below with the blue, red, and yellow polygons in the image below. Each of these values has a different value for attribute A. I have a second layer, which denoted by the bold box in the figure below. I would like to find the average value of attribute A within the area spanned by the bold layer. In the example case it should return an average value of 2 since. How would I do this type of calculation in QGIS 3?
You are looking for the Weighted Arithmetic Mean calculation.
There are many ways to do it and all depend on the form and conditions of the input data.
But in short, all seek to perform the following calculation: Add the product of each value by the area occupied, and divide by the total area.
For the proposal of just three polygons, we can see the manual way of doing it.
My layer "polygons_a" has three fields: "id_a", "area_a" and "value_a".
My layer "polygon_b" has two fields: "id_b" and "area_b".
Make the intersection between "polygon_b" and "polygons_a" layers, keeping the "id_b" fields for the input layer, and the "id_a" and "value_a" fields for the overlay layer.
The output is a new "Intersection" layer. Populate a new field with the area of each intersection feature. I am working with a projected CRS and calculating the planimetric areas with the expression:
area($geometry). I named that field: "area_int".
Now, you can calculate the weighted average value for the "polygon_b", in that layer, populating a new field with the folowing expression:
( attribute( get_feature( 'Intersection', 'id_a', 1), 'value_a') * attribute( get_feature( 'Intersection', 'id_a', 1), 'area_int') + attribute( get_feature( 'Intersection', 'id_a', 2), 'value_a') * attribute( get_feature( 'Intersection', 'id_a', 2), 'area_int') + attribute( get_feature( 'Intersection', 'id_a', 3), 'value_a') * attribute( get_feature( 'Intersection', 'id_a', 3), 'area_int') ) / "area_b"
The expression is just taking the values and areas of the "Intersection" layer, multiplying them and adding the products, to divide the result by the area of the "polygon_b" feature.
An alternative way to accomplish this, providing your source layer is non-overlapping, is to rasterize then extract. In QGIS, you would select
rasterize (Vector to Raster) from the Raster>>Conversion menu. You would select your "Attribute A" as the "Field to use as the Burn in Value", and set some reasonable resolution.
Once this is complete, you will have a raster representation of your base polygons. You can then use
Zonal Statistics from the
Processing toolbar, selecting your new raster layer and the polygon layer you want to summarize.