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.

Vince
  • 20,017
  • 15
  • 45
  • 64
pkry
  • 107
  • 5

1 Answers1

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

Babel
  • 71,072
  • 14
  • 78
  • 208