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 + 99but 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 + 99We 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:
- We used
values[[1]]because we assumed thatvaluesis a list - The elements of
valuescan be vectors. They must have all the same size, and we would need to start withtotal <- rep(0, N)- You have to find what is
Nin this case.
- You have to find what is