r2rs_base/func/
diff.rs

1// "Whatever you do, work at it with all your heart, as working for the Lord,
2// not for human masters, since you know that you will receive an inheritance
3// from the Lord as a reward. It is the Lord Christ you are serving."
4// (Col 3:23-24)
5
6/// Lagged Differences
7///
8/// ## Description:
9///
10/// Returns suitably lagged and iterated differences.
11///
12/// ## Usage:
13///
14/// ```r
15/// diff(x, ...)
16///
17/// ## Default S3 method:
18/// diff(x, lag = 1, differences = 1, ...)
19///
20/// ## S3 method for class 'POSIXt'
21/// diff(x, lag = 1, differences = 1, ...)
22///
23/// ## S3 method for class 'Date'
24/// diff(x, lag = 1, differences = 1, ...)
25/// ```
26///
27/// ## Arguments:
28///
29/// * x: a numeric vector or matrix containing the values to be
30/// differenced.
31///
32/// * lag: an integer indicating which lag to use.
33///
34/// * differences: an integer indicating the order of the difference.
35///
36/// * ...: further arguments to be passed to or from methods.
37///
38/// ## Details:
39///
40/// ‘diff’ is a generic function with a default method and ones for
41/// classes ‘"ts"’, ‘"POSIXt"’ and ‘"Date"’.
42///
43/// ‘NA’'s propagate.
44///
45/// ## Value:
46///
47/// If ‘x’ is a vector of length ‘n’ and ‘differences = 1’, then the
48/// computed result is equal to the successive differences
49/// ‘x\[(1+lag):n\] - x\[1:(n-lag)\]’.
50///
51/// If ‘difference’ is larger than one this algorithm is applied
52/// recursively to ‘x’.Note that the returned value is a vector
53/// which is shorter than ‘x’.
54///
55/// If ‘x’ is a matrix then the difference operations are carried out
56/// on each column separately.
57///
58/// ## References:
59///
60/// Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _The New S
61/// Language_.Wadsworth & Brooks/Cole.
62///
63/// ## See Also:
64///
65/// ‘diff.ts’, ‘diffinv’.
66///
67/// ## Examples:
68///
69/// ```r
70/// diff(1:10, 2)
71/// diff(1:10, 2, 2)
72/// x <- cumsum(cumsum(1:10))
73/// diff(x, lag = 2)
74/// diff(x, differences = 2)
75///
76/// diff(.leap.seconds)
77/// ```
78pub fn diff(x: &[f64]) -> Vec<f64> {
79    x.windows(2).map(|win| win[1] - win[0]).collect()
80}