當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。