Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cumulative difference" function in R

Is there a pre-existing function to calculate the cumulative difference between consequtive values?

Context: this is to estimate the change in altitude that a person has to undergo in both directions on a journey generated by CycleStreet.net.

Reproducible example:

x <- c(27, 24, 24, 27, 28) # create the data

Method 1: for loop

for(i in 2:length(x)){ # for loop way
  if(i == 2) cum_change <- 0
  cum_change <-  Mod(x[i] - x[i - 1]) + cum_change
  cum_change
}
## 7

Method 2: vectorised

diffs <- Mod(x[-1] - x[-length(x)]) # vectorised way
sum(diffs)

## 7

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 RcppRoll.

like image 356
RobinLovelace Avatar asked Dec 15 '22 10:12

RobinLovelace


1 Answers

This is shorter than what you have:

sum(abs(diff(x)))

It's equivalent to your second solution, other than using diff to compute the diffs, and abs instead of Mod, as the input is real (no imaginary component).

like image 128
Matthew Lundberg Avatar answered Jan 10 '23 08:01

Matthew Lundberg