R Tutorial R Charts & Graphs R Statistics R References

R - diff() Function



The R diff() function returns suitably lagged and iterated differences of the argument. The syntax for using this function is given below:

Syntax

diff(x, lag = 1, differences = 1)

Parameters

x Required. Specify a numeric vector or matrix containing the values to be differenced.
lag Optional. Specify an integer indicating which lag to use. Default is 1.
differences Optional. Specify an integer indicating the order of the difference. Default is 1.

Return Value

Returns suitably lagged and iterated differences of the argument.

Example:

The example below shows the usage of diff() function.

vec <- c(11, 22, 34, 47, 61, 76, 92, 109)
 
cat("vec contains:", vec, "\n")

#calculating diff(vec)
cat("\ndiff(vec):", diff(vec), "\n")

#calculating diff(diff(vec)) which is equivalent
#to diff(vec, differences=2)
cat("\ndiff(diff(vec)):", diff(diff(vec)), "\n")
cat("diff(vec, differences=2):", diff(vec, differences=2), "\n")

#calculating diff(vec, lag=2)
cat("\ndiff(vec, lag=2):", diff(vec, lag=2), "\n")

The output of the above code will be:

vec contains: 11 22 34 47 61 76 92 109 

diff(vec): 11 12 13 14 15 16 17 

diff(diff(vec)): 1 1 1 1 1 1 
diff(vec, differences=2): 1 1 1 1 1 1 

diff(vec, lag=2): 23 25 27 29 31 33 

Example:

Consider one more example where diff() function is used with a matrix.

mat <- matrix(c(11, 22, 34, 47, 61, 76, 92, 109, 127), nrow=3)

print(mat)
cat("\n")
print(diff(mat))

The output of the above code will be:

     [,1] [,2] [,3]
[1,]   11   47   92
[2,]   22   61  109
[3,]   34   76  127

     [,1] [,2] [,3]
[1,]   11   14   17
[2,]   12   15   18

❮ R Statistical Functions