# Calculate the difference between Consecutive pair of Elements of a Vector in R Programming – diff() Function

`diff()` function in R Language is used to find the difference between each consecutive pair of elements of a vector.

Syntax: diff(x, lag, differences)

Parameters:
x: vector or matrix
lag: period between elements
differences: Order of difference

Example 1:

 `# R program to find the difference ` `# between each pair of elements of a vector ` ` `  `# Creating a vector ` `x1 <``-` `c(``8``, ``2``, ``5``, ``4``, ``9``, ``6``, ``54``, ``18``) ` `x2 <``-` `c(``1``:``10``) ` `x3 <``-` `c(``-``1``:``-``8``) ` ` `  `# Calling diff() function ` `diff(x1) ` `diff(x2) ` `diff(x3) `

Output:

```  -6   3  -1   5  -3  48 -36
 1 1 1 1 1 1 1 1 1
 -1 -1 -1 -1 -1 -1 -1
```

Example 2:

 `# R program to find the difference ` `# between each pair of elements of a vector ` ` `  `# Creating a vector ` `x1 <``-` `c(``8``, ``2``, ``5``, ``4``, ``9``, ``6``, ``54``, ``18``) ` `x2 <``-` `c(``1``:``10``) ` ` `  `# Calling diff() function ` `diff(x1, lag ``=` `2``, differences ``=` `1``) ` `diff(x2, lag ``=` `1``, differences ``=` `2``) `

Output:

``` -3  2  4  2 45 12
 0 0 0 0 0 0 0 0
```

Here, in the above code, the ‘lag’ tells the period between values, i.e. lag = 2 means, diff is calculated between 1st and 3rd value, 2nd and 4th values, etc. and ‘differences’ tells the order in which `diff()` function is called i.e. differences = 2 means `diff()` function is called twice on the vector.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!