1

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

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)
)
1

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

3
  • In my 3.12.3 i don't see an array_mean function...
    – Kay
    Commented Apr 14, 2021 at 16:56
  • 1
    ..I googled the function: It's not available in the latest stable release 3.16...
    – Kay
    Commented Apr 14, 2021 at 16:58
  • 1
    Sorry, did not realize that it was introduced in 3.18 only - updated my answer accordingly
    – Babel
    Commented Apr 14, 2021 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.