I do not understand what the function diff()
in R does. See this example:
temp = c(10,1,1,1,1,1,1,2,1,1,1,1,1,1,1,3,10) diff(temp)
The above code produces the following output:
[1] -9 0 0 0 0 0 1 -1 0 0 0 0 0 0 2 7
What is the definition of this function?
diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector.
The diff function computes the difference between pairs of consecutive elements of a numeric vector.
a numeric vector or matrix containing the values to be differenced. lag. an integer indicating which lag to use. differences. an integer indicating the order of the difference.
A simple way to view a single (or "first order") difference is to see it as x(t) - x(t-k) where k is the number of lags to go back. Higher order differences are simply the reapplication of a difference to each prior result. In R, the difference operator for xts is made available using the diff() command.
The function calculates the differences between all consecutive values of a vector. For your example vector, the differences are:
1 - 10 = -9 1 - 1 = 0 1 - 1 = 0 . . . 3 - 1 = 2 10 - 3 = 7
The argument differences
allows you to specify the order of the differences.
E.g., the command
diff(temp, differences = 2) [1] 9 0 0 0 0 1 -2 1 0 0 0 0 0 2 5
produces the same result as
diff(diff(temp)) [1] 9 0 0 0 0 1 -2 1 0 0 0 0 0 2 5
Hence, it returns the differences of differences.
The argument lag
allows you to specify the lag.
For example, if lag = 2
, the differences between the third and the first value, between the fourth and the second value, between the fifth and the third value etc. are calculated.
diff(temp, lag = 2) [1] -9 0 0 0 0 1 0 -1 0 0 0 0 0 2 9
It computes the difference between pairs of consecutive elements.
Let's say temp
are observations of some variable, for example temperature readings taken on the hour. Then diff(temp)
will tell you how much the temperature has changed during every hour.
The opposite of diff()
is cumsum()
(cumulative sum):
> temp [1] 10 1 1 1 1 1 1 2 1 1 1 1 1 1 1 3 10 > cumsum(c(10, diff(temp))) [1] 10 1 1 1 1 1 1 2 1 1 1 1 1 1 1 3 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With