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. To get past
NULL values ruining the calculation, first change the values in your cumulative field to
0 with the field calculator. Then, again in the field calculator, write this expression (modifying the relevant layer/field names):
attribute($currentfeature, 'your_frequency_field') + attribute(get_feature_by_id('your_layer', if($id = 1, $id, $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: