I have an attribute table in QGIS in which I would like to calculate the cumulative sum. The table is sorted by N (number of fatalities) and I would like to calculate the cumulative sum on F (frequency of accident), i.e. F_cumulative should be a sum of the current row and the rows above. How should I do this? Can I use a formula in the field calculator?
It can be done with an expression. Bear in mind this only works if the original table is already ordered with N descending as feature IDs increase. Since the result field is empty, we need to get past
NULL values ruining the calculation. We'll use a conditional statement to fill the first line with a different value than the rest, so subsequent calculations can be based a numerical value. In the field calculator, write this expression (modifying the relevant layer/field names):
if($id = 1, attribute($currentfeature, 'your_frequency_field'), attribute($currentfeature, 'your_frequency_field') + attribute(get_feature_by_id('your_layer', $id-1), 'your_cumulative_field'))
This will calculate a cumulative sum in order of feature IDs by fetching the frequency field attribute value of the currently evaluated feature and adding the cumulative frequency field attribute value of the previous feature (with the exception of feature ID = 1 which will fetch its own value:
With a quick mockup of your data, this was my result summing on F and F_cum: