ts_as_tbl: Turn 'ts' into a 'tibble'

View source: R/ts_as_tbl.R

ts_as_tblR Documentation

Turn ts into a tibble

Description

While a method already exists in the tibble package, this method works differently in 2 ways:

  • The time variable associated with the time-series is also returned.

  • The returned tibble is always in long format, even when the time-series is multivariate.

Usage

ts_as_tbl(x, name = "time", value = "value", group = "group")

## Default S3 method:
ts_as_tbl(x, name = "time", value = "value", group = "group")

## S3 method for class 'mts'
ts_as_tbl(x, name = "time", value = "value", group = "group")

## S3 method for class 'xts'
ts_as_tbl(x, name = "time", value = "value", group = "group")

## S3 method for class 'zoo'
ts_as_tbl(x, name = "time", value = "value", group = "group")

## S3 method for class 'timeSeries'
ts_as_tbl(x, name = "time", value = "value", group = "group")

Arguments

x

An object of class ts, mts, zoo, xts or timeSeries.

name

Name of the output time column.

value

Name of the output value column.

group

Name of the output group column when there are multiple series.

Value

A 2-column tibble containing the time index and values for each time index. In the case where there are multiple series, this becomes a 3-column tibble with an additional "group" column added.

See Also

time_ggplot

Examples

library(timeplyr)
library(ggplot2)
library(dplyr)

# Using the examples from ?ts

# Univariate
uts <- ts(cumsum(1 + round(rnorm(100), 2)),
          start = c(1954, 7), frequency = 12)
uts_tbl <- ts_as_tbl(uts)

## Multivariate
mts <- ts(matrix(rnorm(300), 100, 3), start = c(1961, 1), frequency = 12)
mts_tbl <- ts_as_tbl(mts)

uts_tbl %>%
  time_ggplot(time, value)

mts_tbl %>%
  time_ggplot(time, value, group, facet = TRUE)

# zoo example
x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
x <- zoo::zoo(rnorm(5), x.Date)
ts_as_tbl(x)
x <- zoo::zoo(matrix(1:12, 4, 3), as.Date("2003-01-01") + 0:3)
ts_as_tbl(x)


timeplyr documentation built on April 3, 2025, 6:15 p.m.