title: "Cumulative difference" function in R
body: <p>Is there a pre-existing function to calculate the cumulative difference between consequtive values? </p>
  
  <p>Context: this is to estimate the change in altitude that a person has to undergo in both directions on a journey generated by <a href="http://www.cyclestreets.net/api/v1/journey/" rel="nofollow">CycleStreet.net</a>.</p>
  
  <p>Reproducible example:</p>
  
  <pre><code>x &lt;- c(27, 24, 24, 27, 28) # create the data
  </code></pre>
  
  <p>Method 1: for loop</p>
  
  <pre><code>for(i in 2:length(x)){ # for loop way
    if(i == 2) cum_change &lt;- 0
    cum_change &lt;-  Mod(x[i] - x[i - 1]) + cum_change
    cum_change
  }
  ## 7
  </code></pre>
  
  <p>Method 2: vectorised</p>
  
  <pre><code>diffs &lt;- Mod(x[-1] - x[-length(x)]) # vectorised way
  sum(diffs)
  
  ## 7
  </code></pre>
  
  <p>Both seem to work. I'm just wondering if there's another (and more generalisable) implementation in base R or with something like dplyr or <a href="https://cran.r-project.org/web/packages/RcppRoll/index.html" rel="nofollow">RcppRoll</a>.</p>