R语言 计算向量中连续的一对元素之间的差异 – diff()函数
R语言中的 diff() 函数用于查找向量中每一对连续元素之间的差异。
语法: diff(x, lag, differences)
参数:
x: 向量或矩阵
lag: 元素之间的周期
differences: 差异的顺序
例1 :
# R program to find the difference
# between each pair of elements of a vector
# Creating a vector
x1 <- c(8, 2, 5, 4, 9, 6, 54, 18)
x2 <- c(1:10)
x3 <- c(-1:-8)
# Calling diff() function
diff(x1)
diff(x2)
diff(x3)
输出
[1] -6 3 -1 5 -3 48 -36
[1] 1 1 1 1 1 1 1 1 1
[1] -1 -1 -1 -1 -1 -1 -1
例2 :
# R program to find the difference
# between each pair of elements of a vector
# Creating a vector
x1 <- c(8, 2, 5, 4, 9, 6, 54, 18)
x2 <- c(1:10)
# Calling diff() function
diff(x1, lag = 2, differences = 1)
diff(x2, lag = 1, differences = 2)
输出
[1] -3 2 4 2 45 12
[1] 0 0 0 0 0 0 0 0
在这里,在上述代码中,”滞后 “告诉值之间的周期,即 滞后=2 意味着,diff在第1和第3个值之间计算,第2和第4个值之间计算,等等。”差异 “告诉diff()函数被调用的顺序,即 differences=2 意味着diff()函数在矢量上被调用两次。