Learn R Programming

timeplyr (version 1.1.0)

time_expand: A time based extension to tidyr::complete().

Description

A time based extension to tidyr::complete().

Usage

time_expand(
  data,
  time = NULL,
  ...,
  .by = NULL,
  time_by = NULL,
  from = NULL,
  to = NULL,
  sort = TRUE
)

time_complete( data, time = NULL, ..., .by = NULL, time_by = NULL, from = NULL, to = NULL, sort = TRUE, fill = NULL )

Value

A data.frame of expanded time by or across groups.

Arguments

data

A data frame.

time

Time variable.

...

Groups to expand.

.by

(Optional). A selection of columns to group by for this operation. Columns are specified using tidy-select.

time_by

A timespan.

from

Time series start date.

to

Time series end date.

sort

Logical. If TRUE expanded/completed variables are sorted.

fill

A named list containing value-name pairs to fill the named implicit missing values.

Details

This works much the same as tidyr::complete(), except that you can supply an additional time argument to allow for completing implicit time gaps and creating time sequences by group.

Examples

Run this code
library(timeplyr)
library(dplyr)
library(lubridate)
library(nycflights13)
# \dontshow{
.n_dt_threads <- data.table::getDTthreads()
.n_collapse_threads <- collapse::get_collapse()$nthreads
data.table::setDTthreads(threads = 1L)
collapse::set_collapse(nthreads = 1L)
# }
x <- flights$time_hour

time_num_gaps(x) # Missing hours

flights_count <- flights %>%
  fastplyr::f_count(time_hour)

# Fill in missing hours
flights_count %>%
  time_complete(time = time_hour)

# You can specify units too
flights_count %>%
  time_complete(time = time_hour, time_by = "hours")
flights_count %>%
  time_complete(time = as_date(time_hour), time_by = "days") #  Nothing to complete here

# Where time_expand() and time_complete() really shine is how fast they are with groups
flights %>%
  group_by(origin, dest) %>%
  time_expand(time = time_hour, time_by = dweeks(1))
# \dontshow{
data.table::setDTthreads(threads = .n_dt_threads)
collapse::set_collapse(nthreads = .n_collapse_threads)
# }

Run the code above in your browser using DataLab