R diff() function - Calculate Differences
The R diff() function is used to calculate the differences between adjacent elements in a vector.
Differencing is very important in time series analysis, used to calculate changes, growth rates, etc.
The syntax of the diff() function is as follows:
diff(x, lag = 1, differences = 1)
Parameter description:
xInput numeric vector.
lagLag order, default is 1, meaning the difference from the previous element.
differencesDifference order, default is 1. Setting it to 2 means second-order differencing (differencing the differenced result once more).
Example
# Create 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)
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)
Executing the above code produces the following output:
[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 stocks
prices <- c(100, 102, 101, 105, 107, 103, 108)
# Calculate daily price changes
daily_change <- diff(prices)
print(paste("Daily changes:", daily_change))
# Determine daily rise/fall
direction <- ifelse(daily_change > 0, "Rise", "Fall")
print(paste("Rise/Fall direction:", direction))
prices <- c(100, 102, 101, 105, 107, 103, 108)
# Calculate daily price changes
daily_change <- diff(prices)
print(paste("Daily changes:", daily_change))
# Determine daily rise/fall
direction <- ifelse(daily_change > 0, "Rise", "Fall")
print(paste("Rise/Fall direction:", direction))
Executing the above code produces the following output:
[1] "每日变化: 2" "每日变化: -1" "每日变化: 4" [4] "每日变化: 2" "每日变化: -4" "每日变化: 5" [1] "涨跌方向: 涨" "涨跌方向: 跌" "涨跌方向: 涨" [4] "涨跌方向: 涨" "涨跌方向: 跌" "涨跌方向: 涨"Other extensions
R Language Examples