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:
x1 < - c( 8 , 2 , 5 , 4 , 9 , 6 , 54 , 18 )
x2 < - c( 1 : 10 )
x3 < - c( - 1 : - 8 )
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:
x1 < - c( 8 , 2 , 5 , 4 , 9 , 6 , 54 , 18 )
x2 < - c( 1 : 10 )
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.
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!