Avoiding loops in R

前端 未结 3 783
感情败类
感情败类 2021-01-16 08:48

I have decided to learn R. I am trying to get a sense of how to write \"R style\" functions and to avoid looping. Here is a sample situation:

Given a vector a<

3条回答
  •  感动是毒
    2021-01-16 09:33

    You can also use a combination of cumsum and diff to get the sum over sliding windows. You'll need to pad with your own NaN, though:

    > speed <- c(1,1,1,1,1,4,6,3,6,8,9)
    > diff(cumsum(c(0,speed)), 5)/5
    [1] 1.0 1.6 2.6 3.0 4.0 5.4 6.4
    

提交回复
热议问题