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

后端 未结 5 591
难免孤独
难免孤独 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:40

    As they are quarterly returns divide the vector into groups of 4 and calculate for each group.

    tapply(a, gl(length(a)/4, 4), function(x) prod(1 + x) - 1)
    #    1      2 
    #0.2579 0.1800 
    

    The grouping part and calculation part can be done in variety of ways. For example, the above can also be done using split + sapply

    sapply(split(a, gl(length(a)/4, 4)), function(x) prod(1 + x) - 1)
    

    Or grouping can also be done using rep

    tapply(a,rep(seq_along(a), each = 4, length.out = length(a)), 
             function(x) prod(1 + x) - 1)
    

提交回复
热议问题