“Cumulative difference” function in R

天涯浪子 提交于 2019-12-08 06:11:42

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!