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

• Last Updated : 05 Jun, 2020

`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:

```[1]  -6   3  -1   5  -3  48 -36
[1] 1 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:

```[1] -3  2  4  2 45 12
[1] 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.

My Personal Notes arrow_drop_up