5

In QGIS, I have a vector layer with a field listing the names of several polygons features.

I want to calculate the sum of the areas of the polygons in this list, using Field Calculator and displaying the result.

For example my table is :

Names list of polygons area result field: sum of areas
A 10 0
B A,C 20 15
C 5 0

For now I tried using the following function but it doesn't work:

array_sum(
    array_foreach(
        string_to_array("list of polygons", ','),
        area(@element)
        )
    )

but it returns NULL everywhere.

I also tried with :

array_sum(
    array_foreach(
        string_to_array("list of polygons", ','),
        $area
        )
    )

but this gives the area of the current feature.

Any idea where is my mistake?

1 Answer 1

5

The solution

array_sum(
    array_foreach( 
        string_to_array("list of polygons", ','),
        attribute(get_feature (@layer, 'name', @element), 'area')
        )
    )

Explanation

The error in your expression is that you use the function area() with the argument @element, but @element returns the name of a polygon, whereas area() expects a polygon's geometry as input.

The functions area() as well as $area calculate the area from the geometry. You, however, just want to add values that already exist in an attribute called area.

How to implement

  1. So inside the array_foreach() function, you get the name of one of the polygons. You then must identify the feature (line in your attribute table) of this element - like line 2 for feature B in your example. Use get_feature() for that.

  2. Than for this feature, get the value of the attribute named area, using the function attribute().

As you remarked in your comment, be aware where to use double quotes " and where to use single quotes '. Best see help for QGIS expression functions. A field name in single quotes returns the name of the field, a field name in double quotes returns the value stored in that field for the current feature.

1
  • 1
    Wonderful it works! To anyone reading this answer, I was stuck trying to use double quotes for "name" and "area" while the answer has to be followed exactly using single quotes for 'name' / 'area' Thanks Nov 6, 2022 at 22:17

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.