Find Difference of Consecutive Row Values in R (Example Code)
In this article, I’ll demonstrate how to calculate the difference of consecutive rows in R.
Creation of Example Data
data(iris) # Load example data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Load example data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example: Applying diff() Function to Calculate Difference Between Rows
diff(iris$Sepal.Length) # Get row differences # [1] -0.2 -0.2 -0.1 0.4 0.4 -0.8 0.4 -0.6 0.5 0.5 -0.6 0.0 -0.5 1.5 -0.1 # [16] -0.3 -0.3 0.6 -0.6 0.3 -0.3 -0.5 0.5 -0.3 0.2 0.0 0.2 0.0 -0.5 0.1 # [31] 0.6 -0.2 0.3 -0.6 0.1 0.5 -0.6 -0.5 0.7 -0.1 -0.5 -0.1 0.6 0.1 -0.3 # [46] 0.3 -0.5 0.7 -0.3 2.0 -0.6 0.5 -1.4 1.0 -0.8 0.6 -1.4 1.7 -1.4 -0.2 # [61] 0.9 0.1 0.1 -0.5 1.1 -1.1 0.2 0.4 -0.6 0.3 0.2 0.2 -0.2 0.3 0.2 # [76] 0.2 -0.1 -0.7 -0.3 -0.2 0.0 0.3 0.2 -0.6 0.6 0.7 -0.4 -0.7 -0.1 0.0 # [91] 0.6 -0.3 -0.8 0.6 0.1 0.0 0.5 -1.1 0.6 0.6 -0.5 1.3 -0.8 0.2 1.1 # [106] -2.7 2.4 -0.6 0.5 -0.7 -0.1 0.4 -1.1 0.1 0.6 0.1 1.2 0.0 -1.7 0.9 # [121] -1.3 2.1 -1.4 0.4 0.5 -1.0 -0.1 0.3 0.8 0.2 0.5 -1.5 -0.1 -0.2 1.6 # [136] -1.4 0.1 -0.4 0.9 -0.2 0.2 -1.1 1.0 -0.1 0.0 -0.4 0.2 -0.3 -0.3 |
diff(iris$Sepal.Length) # Get row differences # [1] -0.2 -0.2 -0.1 0.4 0.4 -0.8 0.4 -0.6 0.5 0.5 -0.6 0.0 -0.5 1.5 -0.1 # [16] -0.3 -0.3 0.6 -0.6 0.3 -0.3 -0.5 0.5 -0.3 0.2 0.0 0.2 0.0 -0.5 0.1 # [31] 0.6 -0.2 0.3 -0.6 0.1 0.5 -0.6 -0.5 0.7 -0.1 -0.5 -0.1 0.6 0.1 -0.3 # [46] 0.3 -0.5 0.7 -0.3 2.0 -0.6 0.5 -1.4 1.0 -0.8 0.6 -1.4 1.7 -1.4 -0.2 # [61] 0.9 0.1 0.1 -0.5 1.1 -1.1 0.2 0.4 -0.6 0.3 0.2 0.2 -0.2 0.3 0.2 # [76] 0.2 -0.1 -0.7 -0.3 -0.2 0.0 0.3 0.2 -0.6 0.6 0.7 -0.4 -0.7 -0.1 0.0 # [91] 0.6 -0.3 -0.8 0.6 0.1 0.0 0.5 -1.1 0.6 0.6 -0.5 1.3 -0.8 0.2 1.1 # [106] -2.7 2.4 -0.6 0.5 -0.7 -0.1 0.4 -1.1 0.1 0.6 0.1 1.2 0.0 -1.7 0.9 # [121] -1.3 2.1 -1.4 0.4 0.5 -1.0 -0.1 0.3 0.8 0.2 0.5 -1.5 -0.1 -0.2 1.6 # [136] -1.4 0.1 -0.4 0.9 -0.2 0.2 -1.1 1.0 -0.1 0.0 -0.4 0.2 -0.3 -0.3
Further Resources & Related Tutorials
In addition, you might want to have a look at some of the other posts on my website: