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? enter image description here

  • Welcome to GIS SE. As a new user, please be sure to take the short tour to learn about this site's focused Q&A format. – Andy Feb 20 at 15:31

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: 0).

With a quick mockup of your data, this was my result summing on F and F_cum:

enter image description here

  • Thanks, but I want to calculate the cumulative sum of the current row and ALL the rows above. In Excel I calculate it as a sum of F on the current row with F_cumulative on the row above. I tried to change your expression to do this in QGIS but all I get is NULL values. Any suggestions on how I can do this? – Robert K Feb 21 at 10:41
  • @RobertK I modified the answer to address the issues. – Gabriel C. Feb 21 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.