Difference function in R -diff() returns suitably lagged and iterated differences.
Syntax for difference function in R:
diff(x, lag = 1, differences = 1)
- x – numeric vector
- lag-an integer indicating how many lags to use.
- Difference- order of difference
Example of difference function in R with lag 1:
#difference function in R diff(c(2,3,5,18,4,6,4),lag=1)
diff() with lag=1 calculates difference between 2nd element and 1st element and then difference between 3rd element and 2nd element and so on. So the output will be
output:
[1] 1 2 13 -14 2 -2
Example of difference function in R with lag 2:
#difference function in R with lag=2 diff(c(2,3,5,18,4,6,4),lag=2)
diff() with lag=2 calculates difference between 3rd element and 1st element and then difference between 4th element and 2nd element and so on. So the output will be
output:
[1] 3 15 -1 -12 0
Example of difference function in R with lag 1 and differences 2:
#difference function in R with lag=1 and differences=2 diff(c(2,3,5,18,4,6,4),lag=1,differences=2)
First it is differenced with lag=1 and the result is again differenced with lag=1
So the output will be
[1] 1 11 -27 16 -4