What is the diff() function in R?
Overview
The diff() function in R is used to obtain the difference between each element of a vector consecutively.
Syntax
diff(x, lag, differences)
The syntax for the diff() function
Parameter value
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 of2for a vector object(1, 2, 3, 4, 5)means the difference between1and3,2and4, and finally3and5.
differences: This is an integer that indicates the order of the difference. For example, a difference of2means that thediff()function is implemented or called twice on the input vector.
Return value
The diff() function returns a vector or a matrix object.
Example
# 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)
Explanation
- Line 2-3: We create variables
x1andx2representing the vector objects.
- Line 6: We print the first vector object
x1. - Line 8: We implement the
diff()function on the vector object,x1. The result is printed on the console. - Line 12: We print the first vector object
x2. - Line 14: We implement the
diff()function on the vector object,x2. The result is printed on the console.