The diff() function is used to calculate difference between consecutive elements of numeric list, vector or data frame in R. This function returns vector of differences between consecutive elements.
The following method shows how you can do it with syntax.
Method: Use diff() Function
diff(vector)
The following example shows how to use diff() function in R.
Use diff() to Find Difference Between Consecutive Elements of Vector
Let’s apply diff() function on numeric vector:
# Define vector
a <-c(78,85,89,76,74,75)
# Find difference between consecutive elements of vector
diff(a)
Output:
[1] 7 4 -13 -2 1
As we can see diff() function gives difference between elements of vector.