3

In QGIS3+ Field Calculator I am trying to group features by unique values in field 1 then assign a number (no matter the order) from 1 to n (n=number of elements grouped for each unique value in field 1) to populate field 2. The result should be something like:

feature field1  field2
1   Andree  1
2   Andree  2  
3   Andree  3
4   Luka    1
5   Luka    2   

Sounds pretty simple to me and I know how I would it in R, for example. But I really cannot think about a way to do it in QGIS expression builder and without using CASE WHEN-like expressions for every value in field 1; though there are different questions (among others, here or here) that I guess point to the right direction (using aggregation and arrays), I really don't grasp how to:

  • Access/group by every value in field 1
  • Assign a unique value to every feature from an array-type list

There are a couple of doubts above, but I'm looking for an answer to my first query.

1 Answer 1

3

Use this expression (you could also replace $id with feature in your case as this field apparently is also kind of an id):

array_find (
    array_agg( $id, group_by:=field1),
    $id
)+1

enter image description here

1
  • 1
    In array_agg you can additionally order_by a second field
    – hfs
    Commented Oct 13, 2022 at 19:38

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.