3

My layer contains the following fields:

  • "B" is the identifier of a geometry
  • "B_N" are the identifiers of the neighboring geometries of "B".
  • "H" characterizes "B"
  • "B_N_H" characterizes the "B_N"(s)

How could I do the subtraction of "H" and "B_N_H" for each "B_N"?

For example: for b = 56, I would like to get in one column "0, 1, 3, 0" and in another column the maximum value 3 and the corresponding "b_n" identifier 57 for b = 57, I would like to get "0, -3, 0, -1" and the maximum value 3 (absolute value) and the corresponding b_n identifier 56.

enter image description here

1 Answer 1

4

(QGIS 3.22) You can use an expression like this on a Text field in the Field Calculator. It makes an array from the list of neighbours, iterates through that array and subtracts each value from the h field. Finally, it converts the resulting array to a string to be entered in the calculated field.

array_to_string(                   -- convert the final array to a string
    array_foreach(                 -- iterate through array
        string_to_array("b_n_h"),  -- make an array from the contents of "b_n_h" field
        "h" - @element             -- for each element of the b_n_h array, subtract it from the value in field "h"
    ) 
)

enter image description here

For the other column:

"b" || ',' ||                             -- concatenate the value from "b" field with a , and the maximum absolute value as follows

array_max(                                -- get the maximum of the absolute values
    array_foreach( 
        string_to_array("subtraction"),  -- convert the string field value to an array
        abs(@element)                     -- get the absolute value of each array element
    )
)

enter image description here

3
  • thanks @Matt, the 1st part works perfectly. The 2nd part is more complicated: the array_max function is only available from the Qgis 3.18 version. As I am on my personal PC, I just installed version 3.22. The ok button activates, the preview of the result appears at the launch of the command, I have an error message : "An error occurred while evaluating the calculation chain: Unable to convert '' to duplicate". what version of Qgis do you have?
    – fcka
    Feb 5, 2022 at 21:11
  • 1
    I added the my version (3.22) to my answer. Do you have NULL values in one of your fields? I don't know where the error would come from otherwise
    – Matt
    Feb 5, 2022 at 21:16
  • As much for me, I removed all the lists with zeros and it worked perfectly! Congratulations and thank you
    – fcka
    Feb 5, 2022 at 22:05

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.