diff Function in R (2 Examples)
This article shows how to compute the lagged difference of vector elements with the diff() function in the R programming language.
Example Data
vec <- c(5, 3, 7, 9, 4) # Create example vector |
vec <- c(5, 3, 7, 9, 4) # Create example vector
Example 1: Basic Application of diff Function
The diff function calculates the lagged difference of vector elements:
diff(vec) # Apply diff function in R # -2 4 2 -5 |
diff(vec) # Apply diff function in R # -2 4 2 -5
Explanation:
- 3 – 5 = – 2
- 7 – 3 = 4
- 9 – 7 = 2
- 4 – 9 = – 5
Example 2: Compute Difference with lag = 2
By default, the diff function uses a lag of 1. However, we can specify a larger lag with the lag argument of the diff function:
diff(vec, lag = 2) # diff Function with Lag of 2 # 2 6 -3 |
diff(vec, lag = 2) # diff Function with Lag of 2 # 2 6 -3
Explanation:
- 7 – 5 = 2
- 9 – 3 = 6
- 4 – 7 = -3