How to apply a function to every consecutive n elements in a vector

后端 未结 5 535
难免孤独
难免孤独 2021-01-22 09:48

I am trying to convert quarterly returns to yearly returns. Given a vector of quarterly returns, how can this be done?

I am fairly new to R-programming, so I haven\'t r

5条回答
  •  盖世英雄少女心
    2021-01-22 10:21

    An idea via base R,

    sapply(split(a, rep(c(FALSE, TRUE), each = length(a) / 2)), 
                 function(i)((1 + i[1]) * (1 + i[2]) * (1 + i[3]) * (1 + i[4])) - 1)
    
    #    FALSE      TRUE 
    #0.2578742 0.1800339
    

提交回复
热议问题