diff --git a/R/summary-index.R b/R/summary-index.R index c59368a..fe3ba76 100644 --- a/R/summary-index.R +++ b/R/summary-index.R @@ -63,6 +63,30 @@ #' #' # Only evaluate the sum on windows that have the potential to be complete #' slide_index_sum(x, i, before = 2, after = 1, complete = TRUE) +#' +#' # --------------------------------------------------------------------------- +#' # Panel data (grouped rolling operations) +#' +#' # In Stata, the equivalent of grouped rolling means is: +#' # rangestat (mean) roll_mean = sales, int(date -2 0) by(firm) +#' +#' # slider + dplyr replicates this pattern with group_by(): +#' df <- data.frame( +#' firm = rep(c("A", "B"), each = 4), +#' date = as.Date(c( +#' "2020-01-01", "2020-01-02", "2020-01-05", "2020-01-06", +#' "2020-01-01", "2020-01-03", "2020-01-04", "2020-01-07" +#' )), +#' sales = c(10, 12, 15, 13, 20, 22, 18, 25) +#' ) +#' +#' # 3-day rolling mean within each firm, respecting irregular date gaps +#' df$roll_mean <- unlist( +#' lapply(split(df, df$firm), function(g) { +#' slide_index_mean(g$sales, g$date, before = 2) +#' }) +#' ) +#' df slide_index_sum <- function( x, i, diff --git a/man/summary-index.Rd b/man/summary-index.Rd index e1ed27a..7d4af46 100644 --- a/man/summary-index.Rd +++ b/man/summary-index.Rd @@ -183,6 +183,30 @@ slide_index_mean(x, i, before = 2) # Only evaluate the sum on windows that have the potential to be complete slide_index_sum(x, i, before = 2, after = 1, complete = TRUE) + +# --------------------------------------------------------------------------- +# Panel data (grouped rolling operations) + +# In Stata, the equivalent of grouped rolling means is: +# rangestat (mean) roll_mean = sales, int(date -2 0) by(firm) + +# slider + dplyr replicates this pattern with group_by(): +df <- data.frame( + firm = rep(c("A", "B"), each = 4), + date = as.Date(c( + "2020-01-01", "2020-01-02", "2020-01-05", "2020-01-06", + "2020-01-01", "2020-01-03", "2020-01-04", "2020-01-07" + )), + sales = c(10, 12, 15, 13, 20, 22, 18, 25) +) + +# 3-day rolling mean within each firm, respecting irregular date gaps +df$roll_mean <- unlist( + lapply(split(df, df$firm), function(g) { + slide_index_mean(g$sales, g$date, before = 2) + }) +) +df } \seealso{ \code{\link[=slide_sum]{slide_sum()}}