tk_xts: Coerce time series objects and tibbles with date/date-time...

View source: R/coersion-tk_xts.R

tk_xtsR Documentation

Coerce time series objects and tibbles with date/date-time columns to xts.


Coerce time series objects and tibbles with date/date-time columns to xts.


tk_xts(data, select = NULL, date_var = NULL, silent = FALSE, ...)

tk_xts_(data, select = NULL, date_var = NULL, silent = FALSE, ...)



A time-based tibble or time-series object.


Applicable to tibbles and data frames only. The column or set of columns to be coerced to ts class.


Applicable to tibbles and data frames only. Column name to be used to NULL by default. If NULL, function will find the date or date-time column.


Used to toggle printing of messages and warnings.


Additional parameters to be passed to xts::xts(). Refer to xts::xts().


tk_xts is a wrapper for xts::xts() that is designed to coerce tibble objects that have a "time-base" (meaning the values vary with time) to xts class objects. There are three main advantages:

  1. Non-numeric columns that are not removed via select are dropped and the user is warned. This prevents an error or coercion issue from occurring.

  2. The date column is auto-detected if not specified by date_var. This takes the effort off the user to assign a date vector during coercion.

  3. ts objects are automatically coerced if a "timetk index" is present. Refer to tk_ts().

The select argument can be used to select subsets of columns from the incoming data.frame. Only columns containing numeric data are coerced. The date_var can be used to specify the column with the date index. If date_var = NULL, the date / date-time column is interpreted. Optionally, the argument from the underlying xts::xts() function can be used. The user must pass a vector of dates or date-times if is used.

For non-data.frame object classes (e.g. xts, zoo, timeSeries, etc) the objects are coerced using xts::xts().

tk_xts_ is a nonstandard evaluation method.


Returns a xts object.

See Also

tk_tbl(), tk_zoo(), tk_zooreg(), tk_ts()



### tibble to xts: Comparison between tk_xts() and xts::xts()
data_tbl <- tibble::tibble(
    date = seq.Date(as.Date("2016-01-01"), by = 1, length.out = 5),
    x    = rep("chr values", 5),
    y    = cumsum(1:5),
    z    = cumsum(11:15) * rnorm(1))

# xts: Character columns cause coercion issues; must be passed a vector of dates
xts::xts(data_tbl[,-1], = data_tbl$date)

# tk_xts: Non-numeric columns automatically dropped; No need to specify date column

# ts can be coerced back to xts
data_tbl %>%
    tk_ts(start = 2016, freq = 365) %>%

### Using select and date_var
tk_xts(data_tbl, select = y, date_var = date)

### NSE: Enables programming
date_var <- "date"
select   <- "y"
tk_xts_(data_tbl, select = select, date_var = date_var)

timetk documentation built on Sept. 22, 2023, 5:11 p.m.