“累积差异"R中的函数 [英] "Cumulative difference" function in R
问题描述
是否有预先存在的函数来计算结果值之间的累积差异?
Is there a pre-existing function to calculate the cumulative difference between consequtive values?
上下文:这是估计一个人在由 CycleStreet.net.
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.
可重现的例子:
x <- c(27, 24, 24, 27, 28) # create the data
方法一:for循环
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
方法二:矢量化
diffs <- Mod(x[-1] - x[-length(x)]) # vectorised way
sum(diffs)
## 7
两者似乎都有效.我只是想知道在 base R 中是否还有另一个(更通用的)实现,或者像 dplyr 或 RcppRoll.
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.
推荐答案
这比你现有的要短:
sum(abs(diff(x)))
它等同于您的第二个解决方案,除了使用 diff
来计算差异和 abs
而不是 Mod
,因为输入是实部(无虚部).
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).
这篇关于“累积差异"R中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!