如何获得R时间序列中下一行与上一行之间的差异? [英] How to get the difference between next and previous row in an R time series?
本文介绍了如何获得R时间序列中下一行与上一行之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个相当大的时间序列,其中包含约14k对4个变量的观察值(日期
, x
, y
, z
)。
I have a quite large time series comprising around 14k observations of 4 variables (date
, x
, y
, z
).
我怎么(相反)函数 diff(df $ vector,lag = 1)
到计算当前值之间的差( t
)和前一个( t-1
)),为每个值计算下一个值( t + 1
)和上一个值( t-1
)?
How can I, (contrary to the function diff( df$vector, lag = 1)
which computes the difference between the current value (t
) and the previous one (t-1
)), calculate for each value the difference between the next value (t+1
) and the previous value (t-1
)?
推荐答案
因此,为了理解请求...生成一些数据:
So, to understand the request... Generate some data:
set.seed(11)
a = sample(1:10, 10)
数据给出为:
3 1 5 9 7 8 6 4 2 10
需要 T + 1与T-1
:
T = 0 => No computation
T = 1 => 5 - 3 = 2
T = 2 => 9 - 1 = 8
...
T = 9 => 10 - 4 = 6
T = 10 => No computation
随着计算的建立...
With that being established...
#' Future Difference
#'
#' Obtain the lagged difference between X[t+1+lag] - X[t-1-lag]
#' @param x A \code{vec}
#' @param lag A \code{integer} indicating the lag
#' @return A \code{vec} with differences taken at T+lag v. T-lag
#' @examples
#' set.seed(11)
#' a = sample(1:10, 12)
#' fdiff(a)
fdiff = function(x, lag = 1){
# Number of obs
n = length(x)
# Trigger error to prevent subset
if(n < 2+lag){stop("`x` must be greater than `2+lag`")}
# X_(T+1) - X_(T-1)
x[(2+lag):n] - x[1:(n-lag-1)]
}
在 a
上调用会给出:
fdiff(a)
2 8 2 -1 -1 -4 -4 6
这篇关于如何获得R时间序列中下一行与上一行之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文