In QGIS 3, are aggregate functions over a set of array elemnts possible?
As simple as in the form of:
aggregate(array:=array(1,2,3), aggregate:='mean')
I'd use it for the task to get an average for an array of raster values, which I extract at the nodes of a linestring input feature layer. The raster values at the linestring nodes I can retrieve beautifully with the below expression, but obviuosly, there is no way to aggregate those values into on single aggregate for each feature.
with_variable('nodes',
nodes_to_points( $geometry),
array_foreach( generate_series(1, num_points(@nodes)), raster_value(DGM_Slope', 1, point_n(@nodes, @element)))
)
2 Answers 2
array_mean()
is not yet available in the latest release, but I found a neat workaround with eval()
and array_to_String()
:)
with_variable('nodes',
nodes_to_points( $geometry),
eval(
array_to_string(
array_foreach( generate_series(1, num_points(@nodes)), raster_value('Slope', 1, point_n(@nodes, @element)))
, '+')
) * 1/num_points(@nodes)
)
You can simply use the function array_mean(array)
(available since QGIS 3.18) - see the examples in the explanation on the right side of the expression string builder:
array_mean(array(0,1,7,66.6,135.4)) → 42
array_mean(array(0,84,'a','b','c')) → 42
-
In my 3.12.3 i don't see an array_mean function...Kay– Kay2021年04月14日 16:56:14 +00:00Commented Apr 14, 2021 at 16:56
-
1..I googled the function: It's not available in the latest stable release 3.16...Kay– Kay2021年04月14日 16:58:37 +00:00Commented Apr 14, 2021 at 16:58
-
1Sorry, did not realize that it was introduced in 3.18 only - updated my answer accordinglyBabel– Babel2021年04月14日 17:04:18 +00:00Commented Apr 14, 2021 at 17:04