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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.