📜  在 R 编程中计算向量的连续元素对之间的差异 - diff()函数

📅  最后修改于: 2022-05-13 01:55:18.525000             🧑  作者: Mango

在 R 编程中计算向量的连续元素对之间的差异 - diff()函数

R 语言中的diff()函数用于查找向量的每对连续元素之间的差异。

示例 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

在这里,在上面的代码中,'lag' 告诉值之间的周期,即lag = 2表示,计算第 1 和第 3 个值、第 2 和第 4 个值等之间的差异,而 'differences' 告诉diff()函数被调用,即差异 = 2意味着diff()函数在向量上被调用两次。