Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R diff() Function - Computing Differences

R diff() Function - Computing Differences

R Language Examples R Language Examples

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:

Example

Create a vector

x

<-

c

(

10

,

15

,

22

,

30

,

35

,

50

)

First-order difference

result.

diff1

<-

diff

(

x

)

print

(

result.

diff1

)

First-order difference with lag 2

result.

lag2

<-

diff

(

x,

lag

=

2

)

print

(

result.

lag2

)

Second-order difference

result.

diff2

<-

diff

(

x, differences

=

2

)

print

(

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

)

print

(

paste

(

"Daily Changes:"

, daily_change

)

)

Determine daily rises and falls

direction

<-

ifelse

(

daily_change

0

,

"up"

,

"down"

)

print

(

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 R Language Examples