Package 'blockr.ts'

Title: Time Series Data Blocks for blockr
Description: Time series support for blockr. A preview that draws any frame tsbox can read as a chart, and three blocks: transform one series, combine several, and pick a few out of many.
Authors: Christoph Sax [aut, cre]
Maintainer: Christoph Sax <[email protected]>
License: GPL (>= 3)
Version: 0.1.1
Built: 2026-11-19 08:15:18 UTC
Source: https://github.com/cynkra/blockr.ts

Help Index


broom methods for an ETS model

Description

broom covers Arima and seasonal 1.11.0 registers tidy.seas, glance.seas and augment.seas, so ets is the one engine here with no maintained tidier anywhere. sweep has sw_tidy and has not moved in years. These are the twenty lines that close the gap, so the hamburger shows the same two tables whatever fitted the model.

Usage

tidy.ets(x, ...)

glance.ets(x, ...)

Arguments

x

An ets object.

...

Ignored, for compatibility with the generic.

Details

ets() reports no standard errors: the parameters are chosen by numerical likelihood maximisation and the object carries no covariance matrix. The column is absent rather than filled with NA, so nothing downstream mistakes silence for a number.

Value

A data frame: term and estimate for tidy(), one row of fit statistics for glance().


Combine time series

Description

Two or more series in, one block. Side by side, appended in time, chain-linked, or the four arithmetic operators, all of which align on time and id before they compute.

Usage

new_ts_combine_block(method = "c", names = character(), result = NULL, ...)

Arguments

method

One of "c" (side by side), "bind" (append in time), "chain" (chain-link), "divide", "subtract", "multiply" or "add".

names

Series names, one per input slot. Interim: these belong on the link (link$input), and the whole argument goes away when a link can be renamed in the UI.

result

LEGACY. Was the name for the methods that produce one series. Accepted so old boards restore, ignored otherwise: use ts_name() or a downstream rename instead.

...

Forwarded to blockr.core::new_transform_block().

Details

THIS IS THE BLOCK dplyr CANNOT REPLACE, and the reason is the id column.

tsbox::ts_c() is not dplyr::bind_rows(). It builds the id column by deparsing its own arguments, and inside blockr the arguments are called .arg1 and .arg2, so the obvious implementation produces series named .arg1. Where the argument is a nested call, tsbox names the series after the entire source text. Meanwhile bind_rows() on two single-series frames returns twice the rows with no id column and two values per date, and ts_tbl() then errors with "series contains duplicated values in time column", which under this package's convention means the block silently stops drawing.

So: no deparse ever decides an id. Either the frame carries one, or this block supplies one. Each input slot gets a name, defaulted from the series already in that input and editable, and the expression is written with those names.

A slot whose frame already carries an id column needs no name, and will not take one: ts_c(P = x, Q = y) with a two-id x returns a | b | Q, so the ids win and P is dropped silently. That holds for one id as well as for many, which is why the row appears only where length(ts_facts(x)$ids) == 0.

The six methods that reduce to a single series get no naming UI at all. Their result has no id and tsbox calls it value; naming it here would be a rename dressed as a combine, and tsbox cannot name a single series anyway (see ts_name(), which is what such a rename needs).

The arithmetic operators take exactly two inputs and error usefully when the id structures differ, so there is nothing for this block to check.

Examples

new_ts_combine_block(method = "chain")

A built-in time series dataset

Description

Every ts and mts object in an installed package, as a long frame.

Usage

new_ts_dataset_block(dataset = "AirPassengers", package = "datasets", ...)

Arguments

dataset

Name of the object.

package

Package to look in.

...

Forwarded to blockr.core::new_data_block().

Details

This block exists for one reason: blockr.core::new_dataset_block() filters its list to objects that inherit from data.frame, so it never offers AirPassengers. Thirty-one of them ship with R, forty-one series once the multivariate ones are counted out.

The result is tsbox::ts_tbl(), not the ts object, because a frame is what every other block on a board can work on.

Examples

new_ts_dataset_block(dataset = "AirPassengers")

Preview time series as a chart

Description

A blockr.core::tabular_display that draws a chart when a block's result is a time series, and hands everything else to the display the app already had.

Usage

new_ts_display(fallback = NULL)

ts_display

Arguments

fallback

The display for everything else. NULL resolves at render time to blockr.ui::html_table_display when blockr.ui is installed and to blockr.core::minimal_display otherwise, so an app that already had the HTML table preview keeps it.

Details

THE DISPATCH IS ON THE DATA, NOT ON THE BLOCK. This is the whole design. A time series in blockr is any data frame tsbox can read as one, so a dplyr::filter(), a mutate() or the component pulled out of a seasonal adjustment all draw as charts without any of them knowing this package exists.

TSBOX DECIDES, AND ITS REFUSALS ARE THE POINT. A table of orders with a date and an amount is a time series, and on a board where you asked for this display you probably want to see it as one. A table with one row per order and several orders a day is not, and tsbox says so: it errors with "duplicated information" and the frame falls through to fallback. So does anything with two numeric columns, and mtcars, iris and airquality.

Opt in per app. This is the only switch, and a board that does not set it is unaffected.

WHERE TSBOX CANNOT TELL, THE ANSWER IS A dplyr BLOCK, not a block of ours. tsbox goes on column names first and column positions second, so a blockr.dplyr::new_rename_block() that renames a column to time or value is the whole fix. That covers both of the cases worth naming: a frame with two numeric columns, where tsbox will not guess which is the value, and a time column it cannot recognise (a character month holding "2021-01" is not read; the same column called time is parsed into dates). A pivot_longer() result, ⁠date, name, value⁠, needs a select to put the columns back in order.

The alternative, which this replaces, was a ts_block class carrying its own block_ui() and block_output() methods. That put the chart on the block, so a series passing through any block outside this package came out as a table, and undoing the class needed a block of its own (new_ts_to_df_block()).

Turn it on for an app with options(blockr.tabular_display = blockr.ts::ts_display).

Value

new_ts_display() returns a tabular_display; ts_display is one over the app's own preview.

Examples

if (interactive()) {
  options(blockr.tabular_display = blockr.ts::ts_display)
  blockr.core::serve(
    blockr.core::new_static_block(tsbox::ts_tbl(datasets::AirPassengers))
  )
}

Forecast a time series

Description

A frame in, the fitted models out. One block for every engine: pick the target series, pick what fits them, say how far ahead.

Usage

new_ts_forecast_block(
  target = character(),
  engine = "ets",
  h = 12L,
  levels = c(80, 95),
  xreg = character(),
  xreg_mode = "lag",
  lag = numeric(),
  ...
)

Arguments

target

Series to forecast. Empty means all of them.

engine

One of "ets", "arima", "theta" or "var".

h

Horizon, in periods.

levels

Interval levels, in per cent.

xreg

Series to use as regressors, for the engines that take them.

xreg_mode

"lag" or "hold", see details.

lag

Shift for xreg_mode = "lag". Empty means the horizon, the only shift for which nothing has to be invented.

...

Forwarded to blockr.core::new_transform_block().

Details

THE BLOCK RETURNS THE MODEL, not a frame, the same contract the seasonal adjustment block has. A forecast is a point path, two or more interval paths, the fitted values, the residuals and whatever the engine chose, and collapsing all of that to one frame at the block boundary throws away everything the second question needs. new_ts_forecast_series_block() turns it back into a frame when something downstream wants one. The preview draws the model because ts_display dispatches on the data, so a forecast charts wherever it lands.

ONE BLOCK, NOT ONE PER ENGINE. Target, horizon, levels and regressors are the same question whatever fits the model; only the fit differs, and it is a few lines. Four blocks would be four copies of the control machinery, and deciding an ETS should have been an ARIMA would be a delete and two reconnections rather than one click.

THE TARGET IS ALWAYS A MULTISELECT AND THE RESULT IS ALWAYS A NAMED LIST, length one when one series is picked. A control that changes the output type when you touch it is a control that breaks the board downstream, which is why there is no ⁠_multi⁠ twin of this block.

For every engine except VAR, several targets means a loop, which costs nothing. VAR treats the target set as one system, so there the multiselect is the model specification rather than a convenience.

Regressors are the one place this block asks a question it cannot answer for you: a fitted regression cannot predict without values of its regressors over the horizon. "lag" shifts them so the values needed were observed; "hold" carries the last one forward and the resulting interval TREATS THAT GUESS AS AN OBSERVATION, so it is narrower than the truth. That is why "lag" is the default, and why "from a second input", which is the honest third answer, is the one worth building next.

The engines: "ets" is exponential smoothing with the state chosen by AICc, "arima" is auto.arima() and the only one here that takes regressors, "theta" is univariate and hard to beat, and "var" is the joint one.

Examples

new_ts_forecast_block(engine = "arima", h = 24)
new_ts_forecast_block(target = c("mdeaths", "fdeaths"), engine = "var")

Turn fitted models back into a frame

Description

The other half of new_ts_forecast_block(). A model in, a long frame out: the forecast with its intervals, the fitted values, the residuals, the component paths, or one row of accuracy per series.

Usage

new_ts_forecast_series_block(
  what = "forecast",
  levels = numeric(),
  keep_history = TRUE,
  ...
)

Arguments

what

"forecast", "fitted", "residuals", "components" or "accuracy".

levels

Which intervals to keep. Empty means all the fitted ones.

keep_history

Whether the observed series comes along.

...

Forwarded to blockr.core::new_transform_block().

Details

THIS IS WHERE THE INTERVAL CONVENTION LIVES, and putting it here rather than on the forecast block is the whole reason the two are separate. A block that hands out a model has the real forecast object and can read its bounds directly. It is only once somebody wants the forecast as DATA that an interval has to survive as something, and ⁠(id, time, value)⁠ has no column for one.

So it becomes more series: sales, sales_lower_80, sales_upper_80. ts_display pairs them back into a band. The convention is in the id, which is what makes it survive the trip: the frame can go through three dplyr blocks and still draw its band, and a board that never heard of forecasting draws five lines rather than failing.

Rejected: an attribute on the frame. One dplyr::filter() downstream and the band is gone, silently, with the lines still drawn.

"accuracy" is the one output that is not a series. It is one row per target, sorted worst first, because the reason to ask for it is to find which series need a hand.

The rest: "fitted" is in-sample, one value per observed period, "residuals" is observed minus fitted, and "components" is the level, trend and season paths, which ETS has and the other engines do not.

Examples

new_ts_forecast_series_block(what = "accuracy")
new_ts_forecast_series_block(levels = 95, keep_history = FALSE)

Pick a few series out of many

Description

A list with one row per series: what tsbox::ts_summary() knows about it on the left, a sparkline of its shape on the right, and a checkbox. Filter, sort, tick a handful.

Usage

new_ts_pick_block(series = character(), ...)

Arguments

series

Ids to keep. Empty keeps everything.

...

Forwarded to blockr.core::new_transform_block().

Details

THE SPARKLINE IS THE POINT. One Census MARTS download is 168 series, and their names differ by a couple of words each, so a multi-select of 168 ids gives you nothing to choose on. The shape does: scrolling the list you can see which series have the spike and which are flat.

The preview cannot do this job. 168 lines on one chart draw in about three milliseconds and are unreadable, so the problem is never performance.

EACH SPARKLINE IS ONE SVG path, BUILT IN R. 168 charts on one panel is not a thing to do; a path string is a few hundred bytes and the browser draws it with no JavaScript at all. Measured on that file: 168 paths are 146 KB against 334 KB to draw the same series as a chart. Each is scaled to its own range, because the row answers "what shape is this" and not "how big is it".

tsbox::ts_pick() is what the block writes, and it is the right call for two reasons beyond the selection: it keeps the order you picked in, and it renames while it selects, so one control carries both the choice and the legend label. A dplyr::filter(id %in% ...) does the selection and neither of the other two.

Picking nothing passes everything through, so a freshly connected block is a no-op rather than an empty frame.

Examples

new_ts_pick_block(series = c("mdeaths", "fdeaths"))

Transform a time series

Description

One block for all sixteen unary tsbox verbs. Pick the function from the tile grid in the gear; the arguments under it are the ones that function takes, and they are built from the data.

Usage

new_ts_transform_block(
  verb = "pcy",
  base = character(),
  start = character(),
  end = character(),
  by = 1,
  to = character(),
  aggregate = "mean",
  center = TRUE,
  scale = TRUE,
  denominator = 100,
  ...
)

Arguments

verb

One of the keys of the function grid: "pc", "pcy", "pca", "diff", "diffy", "compound", "index", "scale", "span", "lag", "frequency", "regular", "first_of_period", "trend", "na_omit" or "na_interpolation".

base

Base period for "index", as a date string.

start, end

Bounds for "span", as date strings.

by

Shift for "lag", in periods.

to, aggregate

Target frequency and aggregation for "frequency".

center, scale

Passed to tsbox::ts_scale().

denominator

Passed to tsbox::ts_compound().

...

Forwarded to blockr.core::new_transform_block().

Details

ONE BLOCK, NOT SIXTEEN. Every verb here is ⁠f(data, a scalar or two)⁠ and leaves the ids untouched, so sixteen constructors would be sixteen copies of one file. Picking a different function never rewires the board either: a percentage change you decide should have been year-on-year is one click, where two blocks would be a delete and two reconnections. Same call as "histogram is a chart type, not a histogram block".

THE CONTROLS COME FROM tsbox::ts_summary(), which is the part worth the rewrite. The base-period list is bounded by the series, the frequency list offers only frequencies coarser than the one the data has, and "one year" in the lag list is 12 or 4 because the data said so. The block this replaces re-derived a piece of that by hand in every constructor, which is why the span block alone was 319 lines.

Arguments left at their tsbox default are left out of the expression, so what you read back is the choices you made.

Examples

new_ts_transform_block(verb = "pcy")
new_ts_transform_block(verb = "index", base = "1954-01-01")

A fitted forecast, in one line per series

Description

The engine, the horizon, the levels, and then what each target's model turned out to be. That last part is the reason to print one at all: the engine is what you asked for and the method is what you got.

Usage

## S3 method for class 'ts_forecast'
print(x, ...)

Arguments

x

A ts_forecast.

...

Ignored, for compatibility with the generic.

Value

x, invisibly.

Examples

print(ts_forecast(tsbox::ts_tbl(datasets::mdeaths), h = 4))

Register the time series blocks

Description

Six entries, where there were fourteen. The split is by INPUT SHAPE, not by function: sixteen unary tsbox verbs are one block with a function picker, seven ways of combining series are another, and picking a few series out of many is a third because it needs a list you can read rather than a select you cannot. Forecasting is two, because fitting a model and reading one are different shapes, the same split the seas block makes.

Usage

register_ts_blocks()

Fit forecasting models to a long frame

Description

THE BLOCK RETURNS THE MODEL. A frame in, the fitted models out, the same contract the seas block has: the preview draws the model and new_ts_forecast_series_block() turns it back into a frame. The reason is that a forecast is not one series, it is a point path, two or more interval paths, the fitted values, the residuals and whatever the engine chose, and collapsing that to a frame at the block boundary throws away everything the second question needs.

Usage

ts_forecast(
  data,
  target = character(),
  engine = "ets",
  h = 12L,
  levels = c(80, 95),
  xreg = character(),
  xreg_mode = c("lag", "hold"),
  lag = NULL
)

Arguments

data

A frame tsbox can read.

target

Series to forecast. Empty means all of them.

engine

One of names(fc_engines()).

h

Horizon, in periods.

levels

Interval levels, in per cent.

xreg

Series to use as regressors, for the engines that take them.

xreg_mode

How the regressors reach the horizon. "lag" shifts them by lag periods, so the values the forecast needs are already observed. "hold" carries the last observation forward, which UNDERSTATES the interval: it hands the model a guess dressed as an observation.

lag

Shift for xreg_mode = "lag". NULL means h, the only shift for which nothing has to be invented.

Details

ALWAYS A NAMED LIST, length one when one target is picked. A multiselect that changes the output type is a multiselect that breaks the board when you touch it, which is why there is no ⁠_multi⁠ twin of this block.

Value

An object of class ts_forecast: a named list of fits, one per target, each list(engine, model, fc, y).


Turn fitted models back into a frame

Description

THIS IS WHERE THE INTERVAL CONVENTION LIVES, and it lives here rather than on the forecast block because a block that hands out a model has the real forecast object and needs no naming trick to find its bounds. It is only once somebody wants the forecast as DATA that an interval has to survive as something, and ⁠(id, time, value)⁠ has no column for it.

Usage

ts_forecast_frame(
  x,
  what = c("forecast", "fitted", "residuals", "components", "accuracy"),
  levels = NULL,
  keep_history = TRUE
)

Arguments

x

A ts_forecast.

what

"forecast", "fitted", "residuals", "components" or "accuracy".

levels

Which intervals to include. NULL means the ones that were fitted.

keep_history

Whether the observed series comes along.

Details

So it becomes more series: sales, sales_lower_80, sales_upper_80. The chart pairs them back into a band. Unpaired they are ordinary lines, a dplyr::filter() downstream cannot silently destroy them, and a board that never heard of forecasting draws five lines rather than crashing.

Rejected: an attribute on the frame. It survives nothing.

Value

A long frame with id, time and value, except for "accuracy", which is one row per series.


How a fitted model reads

Description

The other side of the chart/table switch, for a result that is a model rather than a frame. ts_resolve() says how a class DRAWS; this says how it READS, and a class that answers both behaves on the time series display wherever it lands.

Usage

ts_model_view(x)

Arguments

x

A block result.

Details

The default returns NULL, which means "not a model, use the app's table preview". That is what keeps this additive: every existing result is unaffected.

Value

A shiny.tag or tagList for a model, NULL for anything else.

Examples

ts_model_view(datasets::AirPassengers)

Give a single series a name

Description

tsbox has no call that names one series. ts_c() builds the id column by deparsing its arguments, so it needs two of them to have anything to build from: ts_c(`A` = x) on a single series drops the name and hands back time and value. Anything that reduces to one series, ts_bind(), ts_chain() and the arithmetic operators, therefore comes back anonymous, and tsbox calls it value.

Usage

ts_name(x, name)

Arguments

x

Anything tsbox can read.

name

The series name.

Details

Returns a data frame rather than the class it was given, because an id column is something only the data frame classes have. A ts object cannot carry a series name at all.

Value

A tibble with id first.

Examples

ts_name(tsbox::ts_pc(datasets::AirPassengers), "Monthly change")

Is this a time series, and if so what does it look like?

Description

ONE CONVERSION ANSWERS BOTH QUESTIONS. Asking "is this a time series" and then converting it would do the same reshape twice, and worse, would ask the question of a 100-row head and answer it for the whole frame: a table that looks like a series in its first rows and has duplicate timestamps later would pass the probe and then throw inside the chart.

Usage

ts_resolve(x)

Arguments

x

A block result.

Details

tsbox decides, and its refusals are the useful part. A real orders table, one row per order and several orders a day, errors with "object contains series with duplicated information" and lands here as NULL. A frame with two numeric columns is not a series either. What survives really is one value per series per period, which is what a line chart can draw.

The ⁠[time]: ... [value]: ...⁠ notice tsbox prints when it picks columns is suppressed: this runs on every render of every block, and the log would be nothing else.

tsbox's canonical column order is id columns first, then time, then value, so the last two are known without asking. Several id columns are pasted into one label, because a chart legend has one dimension.

Resolve a block result to a long frame, or NULL

The seam for results that are not data frames. A model object holds a series but tsbox cannot read it, so a package that produces one adds a method here rather than a branch inside the chart.

Returning NULL is how a method says "not a series", and it is not an error: the display falls through to whatever preview the app already had.

Value

A data frame tsbox can read, or NULL.

Examples

ts_resolve(datasets::AirPassengers)
ts_resolve(datasets::mtcars)

Let the preview draw a model

Description

The seam blockr.ts already has: ts_resolve() is where a package says how its own object turns into something tsbox reads, so the chart needs no branch for forecasts and neither does ts_frame().

Usage

## S3 method for class 'ts_forecast'
ts_resolve(x)

Arguments

x

A ts_forecast.

Details

A forecast resolves to its own extractor's default output, history and all the fitted levels, which is exactly what the chart should draw. The bounds come through as ⁠_lower_80⁠ / ⁠_upper_80⁠ series and the chart pairs them into bands.

Value

A long frame.