Blog of Andrés Aravena
CMB2:

How to make a lot of sums

26 June 2020

This is an issue that I see again and again in your questions, so I will explain it in a different way.

Let’s say that we have a list of values, like 47, 2, 87, 40, 84, 35, 65, 34, 55, 99. We want to calculate their total, that is, the sum of all the values.

We can write

total <- 47 + 2 + 87 + 40 + 84 + 35 + 65 + 34 + 55 + 99

but this gets complicated when we have more numbers. We can do the sum step-by-step

total <- 0
total <- total + 47
total <- total + 2 
total <- total + 87 
total <- total + 40 
total <- total + 84 
total <- total + 35 
total <- total + 65 
total <- total + 34 
total <- total + 55
total <- total + 99

We can see that the final result will be the same. The difference is that we start with an initial value for total, and we update it several times, taking the old value, adding the new number, and storing the updated value in the same place.

We are recycling the variable. By the way, these are called variables because they can vary, or change.

Imagine now that instead of fixed numbers, you have a list. Let’s say that the list is called values, and there are 10 numbers on it. Now we can write

total <- 0
total <- total + values[[1]]
total <- total + values[[2]]
total <- total + values[[3]]
total <- total + values[[4]]
total <- total + values[[5]]
total <- total + values[[6]]
total <- total + values[[7]]
total <- total + values[[8]]
total <- total + values[[9]]
total <- total + values[[10]]

As before, we get the sum of all values at the end. Wise people will find a way to tell the computer to do all the work.

Two final comments: