time_by: Group by a time variable at a higher time unit

View source: R/time_by.R

time_byR Documentation

Group by a time variable at a higher time unit

Description

time_by groups a time variable by a specified time unit like for example "days" or "weeks".
It can be used exactly like dplyr::group_by.

Usage

time_by(data, time, width = NULL, .name = NULL, .add = TRUE)

time_tbl_time_col(x)

Arguments

data

A data frame.

time

Time variable (data-masking).
E.g., a Date, POSIXt, numeric or any time variable.

width

A timespan.

.name

An optional glue specification passed to stringr::glue() which can be used to concatenate strings to the time column name or replace it.

.add

Should the time groups be added to existing groups? Default is TRUE.

x

A time_tbl_df.

Value

A time_tbl_df which for practical purposes can be treated the same way as a dplyr grouped_df.

Examples

library(dplyr)
library(timeplyr)
library(fastplyr)
library(nycflights13)
library(lubridate)

# Basic usage
hourly_flights <- flights %>%
  time_by(time_hour) # Detects time granularity

hourly_flights

monthly_flights <- flights %>%
  time_by(time_hour, "month")
weekly_flights <- flights %>%
  time_by(time_hour, "week")

monthly_flights %>%
  f_count()

weekly_flights %>%
  f_summarise(n = n(), arr_delay = mean(arr_delay, na.rm = TRUE))

# To aggregate multiple variables, use time_aggregate

flights %>%
  f_count(week = time_cut_width(time_hour, months(3)))

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