Nikolai Techow
Nikolai Techow

Reputation: 1

How do I write a loop which sums up my precipitation values

I am looking for a loop which goes over a vector of precipitation values and adds the value to the previous value for example:

precipitation <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)

and I would love to get a vector which adds up the values like this

precipitationSum <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)
print(precipitationSum)

Hope the description makes sense!

Any help would be awesome!

Upvotes: 0

Views: 63

Answers (2)

Dhruv Baid
Dhruv Baid

Reputation: 31

precipitation <- c(0, 2, 0, 0.1, 0.5, 0.6, 0, 1)
precipitation = unlist(precipitation)
print("This loop calculates the partial sums of precipitation")
myList <- unlist(list(1:length(precipitation)))
print(myList)
for(i in 1:length(precipitation)) {
  if(i == 1) {
      myList[i] <- precipitation[i]
  }
  else {
      myList[i] <- myList[i-1] + precipitation[i]
  }
}

print(myList)

Upvotes: 0

Matt
Matt

Reputation: 7385

You can use the cumsum function to calculate the cumulative sum of a vector:

precipitationSum <- cumsum(precipitation)

This gives you the following result:

[1] 0.0 2.0 2.0 2.1 2.6 3.2 3.2 4.2

Upvotes: 2

Related Questions