Here's an example of how to use diff()
on the built-in mtcars
data.frame
. You have to select a column to perform the diff over:
mtcars
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
[..snip..]
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
Calculate the successive differences of e.g. the column "qsec":
diff(mtcars$qsec)
[1] 0.56 1.59 0.83 -2.42 3.20 -4.38 4.16 2.90 -4.60 0.60 -1.50 0.20
[13] 0.40 -0.02 -0.16 -0.40 2.05 -0.95 1.38 0.11 -3.14 0.43 -1.89 1.64
[25] 1.85 -2.20 0.20 -2.40 1.00 -0.90 4.00
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…