diff
Create an Object of Differences

### Description

Finds the difference between adjacent items in the input.

### Usage

    diff(x, lag = 1L, differences = 1L, ...)
    ## Default S3 method:
    diff(x, lag = 1L, differences = 1L, ...)
    ## S3 method for class 'Date':
    diff(x, lag = 1L, differences = 1L, ...)
    ## S3 method for class 'POSIXt':
    diff(x, lag = 1L, differences = 1L, ...)
    ## S3 method for class 'ts':
    diff(x, lag = 1L, differences = 1L, ...)

### Arguments

x | a univariate or multivariate time series object, a vector, or a matrix. Missing values (NAs) are allowed.
lag | an integer that specifies which values to use to calculate the difference. The default setting (lag = 1) calculates the difference between successive elements. If you set lag = 3, the first value in the return value would be calculated by subtracting the first value in the vector from the third value. Non-integer values are truncated to the nearest integer.
differences | an integer that specifies the number of iterations to calculate differences. The default, 1, calculates the difference between successive elements in x. Other values, for example differences = 2, first calculate the difference between successive elements in x, and then calculate the difference between successive elements in the resulting object. Non-integer values are truncated to the nearest integer.
... | additional arguments to pass to function.

### Details

This is a generic function. Methods exist for the time series class "ts", for the date class "Date", and for objects of class "POSIXt".
For a matrix, the difference is calculated by column, rather than row.
Any operation on missing values (NA) produces a missing value (NA). For matrices, differences are performed on individual columns.
Value
returns a vector, a matrix, or time series that is calculated by taking the lag (k) of the input (x), and then iterating through the return value for the number of iterations specified in differences (i).
For example, if y <- diff(x, k), y[i] is x[i]-x[i-k], and length(y) is length(x)-k.
In a time series, the first k times are dropped.
To construct an nth difference, the procedure is iterated n times.
See Also
shift, lag, Arithmetic, Date, POSIXt
Examples

    diff(rep(c(-1, 1), 10), 1, 10)
    ##  [1] -1024  1024 -1024  1024 -1024  1024 -1024  1024 -1024  1024
    x <- runif(10)
    diff(range(x))  # max(x) - min(x)
    diff(matrix(runif(20), nrow = 4), lag = 2)  # for matrix
    diff(ts(Sdatasets::freeny.x, start = 1962.25, frequency = 4))  # for ts class
    ## Date/POSIXt
    diff(as.Date("1970-1-1") + 1:9, lag = 2)
    diff(as.POSIXct("1970-1-1") + 1:9, lag = 3, differences = 1)
    diff(as.POSIXlt("1970-1-1") + 1:9, lag = 1, differences = 3)

Package base version 6.1.5-18
Package Index