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.
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).
来源:https://stackoverflow.com/questions/34209733/cumulative-difference-function-in-r