3

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")))
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Dec 13, 2021 at 20:14
2
  • So AB should be considered to be different from A? Like: 'A, AB, A, AB, C, AB' -> AB? Why not updating to QGIS 3.22? Commented Dec 13, 2021 at 20:19
  • Exactly, AB is different from A or B. If it is too complicated I'll probably have to update... Commented Dec 13, 2021 at 20:25

1 Answer 1

5

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

answered Dec 13, 2021 at 20:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.