knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
The problem arises when we have to use time-series in a data.frame or use time-series
operations like lag
and diff
for numeric vectors in a data.frame. Let's look into
an example.
library(transx)
First, wee restrict tibble printing options to minimize the space occupied.
library(dplyr) options(tibble.print_min = 3)
Let's load the economics dataset from ggplot2
for illustration.
econ <- ggplot2::economics econ
Then, we are going to use some stats
functions:
mutate(econ, pop_lag = stats::lag(as.ts(pop)))
base::lag
only works on ts
objects. However, dplyr has thought about this problem
mutate(econ, pop_lag = dplyr::lag(pop))
However, this problem extends to all the univariate functions that are applied in the same manner in a data.frame. For example
mutate(econ, pop_diff = base::diff(pop))
The idea for transx
is coming from the need to construct wrapper functions.
diffx <- function(x, ...) x - dplyr::lag(x, ... ) mutate(econ, pop_diff = diffx(pop))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.