Applying function to consecutive subvectors of equal size

前端 未结 3 2063
花落未央
花落未央 2021-01-13 20:08

I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as sum, consecutively to a subvector of consecutive K e

3条回答
  •  温柔的废话
    2021-01-13 20:37

    You could try this as well. This works nicely even if you want to include overlapping intervals, as controlled by by, and as a bonus, returns the intervals over which each value is derived:

    library (gtools)
    v2 <- running(v, fun=sum, width=3, align="left", allow.fewer=TRUE, by=3)
    
    v2
    1:3 4:6 7:8 
      6  15  15 
    

提交回复
热议问题