[Stable]

difference(x, lag = 1, differences = 1, default = NA, order_by = NULL)

Arguments

x

Vector of values

lag

A positive integer indicating which lag to use.

differences

A positive integer indicating the order of the difference.

default

Value used for non-existent rows. Defaults to NA.

order_by

Override the default ordering to use another vector or column

Value

A numeric vector of the same length as x.

See also

Examples

# examples from base
difference(1:10, 2)
#>  [1] NA NA  2  2  2  2  2  2  2  2
difference(1:10, 2, 2)
#>  [1] NA NA NA NA  0  0  0  0  0  0
x <- cumsum(cumsum(1:10))
difference(x, lag = 2)
#>  [1]  NA  NA   9  16  25  36  49  64  81 100
difference(x, differences = 2)
#>  [1] NA NA  3  4  5  6  7  8  9 10
# Use order_by if data not already ordered (example from dplyr)
library(dplyr, warn.conflicts = FALSE)
tsbl <- tsibble(year = 2000:2005, value = (0:5)^2, index = year)
scrambled <- tsbl %>% slice(sample(nrow(tsbl)))
#> Warning: Current temporal ordering may yield unexpected results.
#>  Suggest to sort by ``, `year` first.

wrong <- mutate(scrambled, diff = difference(value))
#> Warning: Current temporal ordering may yield unexpected results.
#>  Suggest to sort by ``, `year` first.
#> Warning: Current temporal ordering may yield unexpected results.
#>  Suggest to sort by ``, `year` first.
arrange(wrong, year)
#> # A tsibble: 6 x 3 [1Y]
#>    year value  diff
#>   <int> <dbl> <dbl>
#> 1  2000     0    -4
#> 2  2001     1   -15
#> 3  2002     4    NA
#> 4  2003     9   -16
#> 5  2004    16    16
#> 6  2005    25    24

right <- mutate(scrambled, diff = difference(value, order_by = year))
#> Warning: Current temporal ordering may yield unexpected results.
#>  Suggest to sort by ``, `year` first.
#> Warning: Current temporal ordering may yield unexpected results.
#>  Suggest to sort by ``, `year` first.
arrange(right, year)
#> # A tsibble: 6 x 3 [1Y]
#>    year value  diff
#>   <int> <dbl> <dbl>
#> 1  2000     0    NA
#> 2  2001     1     1
#> 3  2002     4     3
#> 4  2003     9     5
#> 5  2004    16     7
#> 6  2005    25     9