i <- as.Date("2019-01-28") + 0:5
# Split `i` into 2-day periods to apply `.f` to
slide_period(i, i, "day", identity, .every = 2)
# Or into 1-month periods
slide_period(i, i, "month", identity)
# Now select:
# - The current 2-day period
# - Plus 1 2-day period before the current one
slide_period(i, i, "day", identity, .every = 2, .before = 1)
# Alter the `origin` to control the reference date for
# how the 2-day groups are formed
origin <- as.Date("2019-01-29")
slide_period(i, i, "day", identity, .every = 2, .origin = origin)
# This can be useful for, say, monthly averages
daily_sales <- c(2, 5, 3, 6, 9, 4)
slide_period_dbl(daily_sales, i, "month", mean)
# If you need the index, slide over and return a data frame
sales_df <- data.frame(i = i, sales = daily_sales)
slide_period_dfr(
sales_df,
sales_df$i,
"month",
~data.frame(
i = max(.x$i),
sales = mean(.x$sales)
)
)
# One of the most unique features about `slide_period()` is that it is
# aware of how far apart elements of `.i` are in the `.period` you are
# interested in. For example, if you do a monthly slide with `i2`, selecting
# the current month and 1 month before it, then it will recognize that
# `2019-02-01` and `2019-04-01` are not beside each other, and it won't
# group them together.
i2 <- as.Date(c("2019-01-01", "2019-02-01", "2019-04-01", "2019-05-01"))
slide_period(i2, i2, "month", identity, .before = 1)
Run the code above in your browser using DataLab