R diff() Function - Computing Differences
The R diff() function is used to compute the differences between adjacent elements in a vector.
Differencing is very important in time series analysis, used to compute changes, growth rates, and so on.
The syntax of the diff() function is as follows:
diff(x, lag = 1, differences = 1)
Parameter Description:
-
x Input numeric vector.
-
lag The lag order, defaulting to 1, indicating the difference from the previous element.
-
differences The difference order, defaulting to 1. Setting it to 2 means a second-order difference (differencing the result again).
Example
Create a vector
x
<-
c
(
10
,
15
,
22
,
30
,
35
,
50
)
First-order difference
result.
diff1
<-
diff
(
x
)
(
result.
diff1
)
First-order difference with lag 2
result.
lag2
<-
diff
(
x,
lag
=
2
)
(
result.
lag2
)
Second-order difference
result.
diff2
<-
diff
(
x, differences
=
2
)
(
result.
diff2
)
The output of the code above is:
[1] 5 7 8 5 15
[1] 12 15 13 20
[1] 2 1 -3 10
diff() is often used in stock price analysis:
Example
Simulate daily closing prices of a stock
prices
<-
c
(
100
,
102
,
101
,
105
,
107
,
103
,
108
)
Compute daily price changes
daily_change
<-
diff
(
prices
)
(
paste
(
"Daily Changes:"
, daily_change
)
)
Determine daily rises and falls
direction
<-
ifelse
(
daily_change
0
,
"up"
,
"down"
)
(
paste
(
"Direction of Change:"
, direction
)
)
The output of the code above is:
[1] "每日变化: 2" "每日变化: -1" "每日变化: 4"
[4] "每日变化: 2" "每日变化: -4" "每日变化: 5"
[1] "涨跌方向: 涨" "涨跌方向: 跌" "涨跌方向: 涨"
[4] "涨跌方向: 涨" "涨跌方向: 跌" "涨跌方向: 涨"
R Language Examples