The diff() function in R is used to obtain the difference between each element of a vector consecutively.
diff(x, lag, differences)
The diff() function takes the following parameter values:
x: This is a numeric vector or matrix object containing the values to be differenced.lag: This is an integer indicating the lag to be used. In other words, it tells the period between each element of a vector object. For example, a lag of 2 for a vector object (1, 2, 3, 4, 5)means the difference between 1 and 3, 2 and 4, and finally 3 and 5.differences: This is an integer that indicates the order of the difference. For example, a difference of 2 means that the diff() function is implemented or called twice on the input vector.The diff() function returns a vector or a matrix object.
# creating vector objectsx1 <- c(6, 1, 3, 4, 9, 9, 20, 18)x2 <- c(1:5)# printing the input vector objectx1# Calling diff() functiondiff(x1, lag = 2, differences = 1)# printing the input vector objectx2# calling the diff() functiondiff(x2, lag = 1, differences = 2)
x1 and x2 representing the vector objects.x1.diff() function on the vector object, x1. The result is printed on the console.x2.diff() function on the vector object, x2. The result is printed on the console.