Blg Khalil
Blg Khalil

Reputation: 349

If statement in R gives weird results

I have a time series of 741 values and I'm trying to extract in each non-overlapping block the maximum value in it. In my case the first block contains the first 10 values, the second contains from the 11th to the 20th value, the third from the 21st to the 30th while the last is the block containing one value, the 741th value.

The first three values of the data:

log_returns <- c(0, 0.00394232277373519, 0.0287804332171326, ...)

My attempt:

block_maxima = c()
for (i in 1:741){if (i %% 10 == 0) {block_maxima <- c(block_maxima, max(log_returns[i-9: i]))
}}

This code gives me the result:

c(0, 0.0287804332171326, 0.0287804332171326, ...)

And I want:

c(0.0287804332171326, 0.0236378411885054, 0.0185381209989108, ...)

Can someone point me to the mistake I made in my code? Thanks in advance.

Upvotes: 1

Views: 35

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388797

Looking at your code it seems you are trying to take max of 10 values at a time. Instead of looping over each element and then performing calculation for every 10th element you can create a group of every 10 elements and find max in them. One way would be to do this using tapply.

block_maxima  <- tapply(log_returns, ceiling(seq_along(log_returns)/10), max)

Upvotes: 1

akrun
akrun

Reputation: 886938

We could wrap the i-9 inside a () to avoid the issue of operator precedence

block_maxima = c()
for (i in 1:741){
        if (i %% 10 == 0) {
     block_maxima <- c(block_maxima, max(log_returns[(i-9): i]))
   }
   }

Upvotes: 1

Related Questions