diff Function in R (2 Examples)

This article shows how to compute the lagged difference of vector elements with the diff() function in the R programming language.

Example Data

vec <- c(5, 3, 7, 9, 4)           # Create example vector

Example 1: Basic Application of diff Function

The diff function calculates the lagged difference of vector elements:

diff(vec)                         # Apply diff function in R
# -2  4  2 -5

Explanation:

  • 3 – 5 = – 2
  • 7 – 3 = 4
  • 9 – 7 = 2
  • 4 – 9 = – 5

Example 2: Compute Difference with lag = 2

By default, the diff function uses a lag of 1. However, we can specify a larger lag with the lag argument of the diff function:

diff(vec, lag = 2)                # diff Function with Lag of 2
# 2  6 -3

Explanation:

  • 7 – 5 = 2
  • 9 – 3 = 6
  • 4 – 7 = -3

Video Explanation: The diff Function in R

YouTube

By loading the video, you agree to YouTube’s privacy policy.
Learn more

Load video

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top