Learn R Programming

tsibble (version 0.5.3)

difference: Lagged differences

Description

Lagged differences

Usage

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

Arguments

x

A numeric vector.

lag

An positive integer indicating which lag to use.

differences

An 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.

Value

A numeric vector of the same length as x.

See Also

dplyr::lead and dplyr::lag

Examples

Run this code
# NOT RUN {
# examples from base
difference(1:10, 2)
difference(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
difference(x, lag = 2)
difference(x, differences = 2)
# Use order_by if data not already ordered (example from dplyr)
tsbl <- tsibble(year = 2000:2005, value = (0:5) ^ 2, index = year)
scrambled <- tsbl %>% slice(sample(nrow(tsbl)))

wrong <- mutate(scrambled, diff = difference(value))
arrange(wrong, year)

right <- mutate(scrambled, diff = difference(value, order_by = year))
arrange(right, year)
# }

Run the code above in your browser using DataLab