Reputation: 189
I am trying to calculate a 8-days accumulated rainfall, with this code, but it seems to not work well.
chuva$Precipitacao it is my vector of daily rainfall, of length 5601.
rain<-chuva$Precipitacao
j=1
rain8<-vector()
for (i in 1:800){
rain8<-rbind(rain8, (rain[j]+rain[j+1]+rain[j+2]+rain[j+3]+
rain[j+4]+rain[j+5]+rain[j+6]+rain[j+7]));
j=i+7
}
Upvotes: 1
Views: 1442
Reputation: 2827
You can just do it like this:
## if you want to calculate moving sum of 8 days
rain <- chuva$Precipitacao
rain8 <- vector()
for (i in rain[1:5594]){
rain8 <- c(rain8, sum(rain[i:i + 7]))
}
## if you want to calculate sum for each separate period of 8 days
rain <- chuva$Precipitacao
rain8 <- vector()
for (i in seq(1, length(rain), 7)){
rain8 <- c(rain8, sum(rain[i:i + 7]))
}
Upvotes: 2
Reputation: 410
You could try the following one liner rollapply function from the zoo package.
rain8<-rollapply(rain, 'your main vector
8, 'The number of consecutive data points
sum) 'The function you want to apply
Upvotes: 4