huge
huge

Reputation: 31

Loop to sum observation of a time serie in R

I'm sure this is very obvious but i'm a begginer in R and i spent a good part of the afternoon trying to solve this...

I'm trying to create a loop to sum observation in my time serie in steps of five.

for example :

input:
1 2 3 4 5 5 6 6 7 4 5 5 4 4 5 6 5 6 4 4

output: 15 28 23 25

My time serie as only one variable, and 7825 obserbations.

The finality of the loop is to calculate the weekly realized volatility. My observations are squared returns. Once i'll have my loop, i'll be able to extract the square root and have my weekly realized volatility.

Thank you very much in advance for any help you can provide.

H.

Upvotes: 1

Views: 101

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101568

Here is another base R option using sapply + split

> sapply(split(x,ceiling(seq_along(x)/5)),sum)
 1  2  3  4
15 28 23 25

Data

x <- c(1, 2, 3, 4, 5, 5, 6, 6, 7, 4, 5, 5, 4, 4, 5, 6, 5, 6, 4, 4)

Upvotes: 2

akrun
akrun

Reputation: 887168

We can create a grouping variable with gl and use that to get the sum in tapply

tapply(input, as.integer(gl(length(input), 5, length(input))), 
          FUN = sum, na.rm = TRUE)
# 1  2  3  4 
# 15 28 23 25 

data

input <- scan(text = "1 2 3 4 5 5 6 6 7 4 5 5 4 4 5 6 5 6 4 4", what = numeric())

Upvotes: 4

Related Questions