4

In QGIS, I have a column separated by comma (shown by column "lengths"). I want to sum up elements in it for each row. The column is a text field string.

attribute table

0

1 Answer 1

7

You can use arrays in fieldcalculator for this:

array_sum(array_foreach(string_to_array("lengths",','),to_real(@element)))
  1. Turn the string into an array
  2. Iterate over the array and convert the string elements to an integer or double
  3. Build the sum (array_sum() available since QGIS 3.18)

To catch errors on invalid "numbers", you can use try():

array_sum(array_foreach(string_to_array("lengths",','),try(to_real(@element),0)))
2
  • I had an error while running it: Evaluation error in expression "array_sum(array_foreach(string_to_array("lengths",','),to_real(@element)))": Cannot convert '' to double Execution failed after 0.30 seconds
    – Eren E
    Jun 12, 2022 at 20:30
  • 3
    That means that at least one of the fields lengths is empty. Change the expression to convert such cases to NULL, keeping the expression by @MrXsquared otherwiese. Use this expression: if (lengths is NULL, NULL, array_sum (array_foreach (string_to_array ("lengths",','), to_real (@element))))
    – Babel
    Jun 12, 2022 at 20:39

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.