I need to identify the majority of a string in an attribute field. For example 'A,AB,C,A' -> 'A'
Since QGIS 3.18 the function array_majority()
is available.
However, I use the latest stable version 3.16 and I am wondering if something similar can be done?
Something like:
array_to_string(majority(string_to_array("sumEHZ")))
1 Answer 1
In QGIS 3.16, you can use this expression, where text
is the field containing the text you want to replace:
with_variable (
'var',
'array_foreach (
array_distinct (string_to_array ("text")),
with_variable (
''arr'',
@element,
array_length (
array_filter (
string_to_array("text"),
@element=@arr
)
)
)
)',
array_get (
array_distinct (string_to_array("text")),
array_find (
eval(@var),
array_get (
array_sort (
eval(@var),0
),0
)
)
)
)
Expression edited, the repeating part from the initial expression is created as a variable var
and called twice with eval(@var)
to make the expression a bit shorter. See the screenshot for the (otherwise unchanged) initial expression:
enter image description here
AB
should be considered to be different fromA
? Like:'A, AB, A, AB, C, AB' -> AB
? Why not updating to QGIS 3.22?AB
is different fromA
orB
. If it is too complicated I'll probably have to update...