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.
1 Answer
You can use arrays in fieldcalculator for this:
array_sum(array_foreach(string_to_array("lengths",','),to_real(@element)))
- Turn the string into an array
- Iterate over the array and convert the string elements to an integer or double
- 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)))
-
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 EJun 12, 2022 at 20:30
-
3That means that at least one of the fields
lengths
is empty. Change the expression to convert such cases toNULL
, 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))))
– BabelJun 12, 2022 at 20:39