当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 diff()用法及代码示例


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

用法: 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

在这里,在上面的代码中,‘lag’ 告诉值之间的周期,即滞后 = 2 表示,差异是在第 1 个和第 3 个值、第 2 个和第 4 个值之间计算的,等等。 ‘differences’ 告诉在其中的顺序diff()函数被调用,即差异 = 2手段diff()函数在向量上被调用两次。




相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Calculate the difference between Consecutive pair of Elements of a Vector in R Programming – diff() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。