Farah
Farah

Reputation: 1

adding consecutive value of rainfall in R according to date

I have a dataset named "Dhaka" that looks like below:

  1. time precipitation
  2. 01/01/1998 5
  3. 01/02/1998 2
  4. 01/03/1998 4
  5. 01/04/1998 6
  6. 01/05/1998 7
  7. 01/06/1998 11

I want to do the consecutive summation of the precipitation in a way so that it sums the precipitation of the three days (precipitation of two days before the exact date+ exact date precipitation).
The output may look like below:

  1. time precipitation
  2. 01/01/1998 5
  3. 01/02/1998 7 = 5+2
  4. 01/03/1998 11 =5+2+4
  5. 01/04/1998 12 =2+4+6
  6. 01/05/1998 17 = 4+6+7
  7. 01/06/1998 24 = 6+7+11

the first value will be the same, second value will be the sum of the first and second value and the rest will be the summation of three precipitation value. I used

rollapply(precipitation, 3, sum)

but it did not give value date wise.

Upvotes: 0

Views: 49

Answers (1)

C-x C-c
C-x C-c

Reputation: 1311

What you're looking for is cumsum:

library(data.table)
Dhaka <- data.table(Dhaka)[order(time)]

totalSum <- Dhaka[, cumsum(precipitation)]

Take the difference:

diffSum <- diff(totalSum, lag = 3)
finalSum <- c(totalSum[1:3], diffSum)

Dhaka[, sums := finalSum]

Upvotes: 1

Related Questions