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 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.

Return value

The diff() function returns a vector or a matrix object.

Example

# creating vector objects
x1 <- c(6, 1, 3, 4, 9, 9, 20, 18)
x2 <- c(1:5)
# printing the input vector object
x1
# Calling diff() function
diff(x1, lag = 2, differences = 1)
# printing the input vector object
x2
# calling the diff() function
diff(x2, lag = 1, differences = 2)

Explanation

  • Line 2-3: We create variables x1 and x2 representing 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.

Free Resources