complete_periods: Given a cumulative metric, add dates for the end of each...

Description Usage Arguments Examples

View source: R/complete-periods.R

Description

Some metrics like ARR are measured cumulatively, so in order to create a bar plot per month or quarter we need to pick the last value from each period. For example, the ARR for January 2019 would be measured as of 2019-01-31. Analogously to the tidyr function complete(), this adds rows representing each period present in the data.

Usage

1
2
3
4
5
6
complete_periods(
  metric,
  periods = c("month"),
  add_incomplete = FALSE,
  week_start = getOption("lubridate.week.start", 1)
)

Arguments

metric

A metric table in wide format, containing "date" and "period" columns as well as one or more dimensions and metric values.

periods

Vector of periods to add: one or more of "week", "month", "quarter" or "year".

add_incomplete

If TRUE a value of the running incomplete period will be added.

week_start

when unit is weeks, specifies the reference day. 7 represents Sunday and 1 represents Monday. Note that we use a default of 1 instead of 7, in order to be consistent with SQL.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
library(dplyr)

flights <- nycflights13::flights %>%
  mutate(date = as.Date(ISOdate(year, month, day)))

# Include number and cumulative number of flights
cumulative_summary <- flights %>%
  cross_by_periods(periods = "day") %>%
  summarize(nb_flights = n()) %>%
  arrange(date) %>%
  mutate(cumulative_flights = cumsum(nb_flights)) %>%
  ungroup()

# Have periods for week and month as well, representing the end of that period
library(ggplot2)

cumulative_day_week_month <- cumulative_summary %>%
  complete_periods(periods = c("week", "month"))

cumulative_day_week_month %>%
  ggplot(aes(date, cumulative_flights, color = period)) +
  geom_point()

datacamp/tidymetrics documentation built on March 21, 2021, 3:28 a.m.