difference: Lagged differences

View source: R/time-wise.R

differenceR Documentation

Lagged differences

Description

[Stable]

Usage

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

Arguments

x

A vector

lag

A positive integer indicating which lag to use.

differences

A positive integer indicating the order of the difference.

default

The value used to pad x back to its original size after the lag or lead has been applied. The default, NULL, pads with a missing value. If supplied, this must be a vector with size 1, which will be cast to the type of x.

order_by

An optional secondary vector that defines the ordering to use when applying the lag or lead to x. If supplied, this must be the same size as x.

Value

A numeric vector of the same length as x.

See Also

dplyr::lead and dplyr::lag

Examples

# 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)
library(dplyr, warn.conflicts = FALSE)
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)

tsibble documentation built on June 27, 2024, 5:06 p.m.