Skip to content

Commit c72bc13

Browse files
committed
feat(epi_slide_opt)!: add .prefix =, .suffix =, .new_col_names =
- BREAKING CHANGE: adjust default output column naming scheme, disallow overwriting columns.
1 parent c75de38 commit c72bc13

File tree

7 files changed

+182
-41
lines changed

7 files changed

+182
-41
lines changed

NAMESPACE

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ importFrom(checkmate,assert_list)
114114
importFrom(checkmate,assert_logical)
115115
importFrom(checkmate,assert_numeric)
116116
importFrom(checkmate,assert_scalar)
117+
importFrom(checkmate,assert_string)
117118
importFrom(checkmate,checkInt)
118119
importFrom(checkmate,check_atomic)
119120
importFrom(checkmate,check_data_frame)
@@ -176,6 +177,7 @@ importFrom(dplyr,summarize)
176177
importFrom(dplyr,tibble)
177178
importFrom(dplyr,ungroup)
178179
importFrom(ggplot2,autoplot)
180+
importFrom(glue,glue)
179181
importFrom(lifecycle,deprecated)
180182
importFrom(lubridate,as.period)
181183
importFrom(lubridate,days)
@@ -198,6 +200,7 @@ importFrom(rlang,env)
198200
importFrom(rlang,expr_label)
199201
importFrom(rlang,f_env)
200202
importFrom(rlang,f_rhs)
203+
importFrom(rlang,is_bare_integerish)
201204
importFrom(rlang,is_environment)
202205
importFrom(rlang,is_formula)
203206
importFrom(rlang,is_function)
@@ -206,6 +209,7 @@ importFrom(rlang,is_quosure)
206209
importFrom(rlang,list2)
207210
importFrom(rlang,missing_arg)
208211
importFrom(rlang,new_function)
212+
importFrom(rlang,quo_get_env)
209213
importFrom(rlang,quo_is_missing)
210214
importFrom(rlang,sym)
211215
importFrom(rlang,syms)
@@ -230,3 +234,4 @@ importFrom(tidyselect,starts_with)
230234
importFrom(tsibble,as_tsibble)
231235
importFrom(utils,capture.output)
232236
importFrom(utils,tail)
237+
importFrom(vctrs,vec_data)

R/epi_df.R

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ as_epi_df.tbl_df <- function(
232232
as_of,
233233
other_keys = character(),
234234
...) {
235-
# possible standard substitutions for time_value
236235
x <- rename(x, ...)
237236
x <- guess_column_name(x, "time_value", time_column_names())
238237
x <- guess_column_name(x, "geo_value", geo_column_names())
@@ -282,11 +281,11 @@ as_epi_df.tbl_df <- function(
282281
cli_abort("as_epi_df: `other_keys` can't include \".time_value_counts\"")
283282
}
284283

285-
duplicated_time_values <- x %>%
286-
group_by(across(all_of(c("geo_value", "time_value", other_keys)))) %>%
287-
filter(dplyr::n() > 1) %>%
288-
ungroup()
289-
if (nrow(duplicated_time_values) > 0) {
284+
if (anyDuplicated(x[c("geo_value", "time_value", other_keys)])) {
285+
duplicated_time_values <- x %>%
286+
group_by(across(all_of(c("geo_value", "time_value", other_keys)))) %>%
287+
filter(dplyr::n() > 1) %>%
288+
ungroup()
290289
bad_data <- capture.output(duplicated_time_values)
291290
cli_abort(
292291
"as_epi_df: some groups in the data have duplicated time values. epi_df requires a unique time_value per group.",

R/epiprocess-package.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#' @importFrom checkmate anyInfinite anyMissing assert assert_character
77
#' @importFrom checkmate assert_class assert_data_frame assert_int assert_list
88
#' @importFrom checkmate assert_logical assert_numeric assert_scalar checkInt
9+
#' @importFrom checkmate assert_string
910
#' @importFrom checkmate check_atomic check_data_frame expect_class test_int
1011
#' @importFrom checkmate check_names
1112
#' @importFrom checkmate test_subset test_set_equal vname
@@ -16,6 +17,8 @@
1617
#' @importFrom dplyr select
1718
#' @importFrom lifecycle deprecated
1819
#' @importFrom rlang %||%
20+
#' @importFrom rlang is_bare_integerish
21+
#' @importFrom vctrs vec_data
1922
## usethis namespace: end
2023
NULL
2124

R/slide.R

Lines changed: 89 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ get_before_after_from_window <- function(window_size, align, time_type) {
537537
#'
538538
#' @template basic-slide-params
539539
#' @param .col_names <[`tidy-select`][dplyr_tidy_select]> An unquoted column
540-
#' name(e.g., `cases`), multiple column names (e.g., `c(cases, deaths)`),
540+
#' name (e.g., `cases`), multiple column names (e.g., `c(cases, deaths)`),
541541
#' [other tidy-select expression][tidyselect::language], or a vector of
542542
#' characters (e.g. `c("cases", "deaths")`). Variable names can be used as if
543543
#' they were positions in the data frame, so expressions like `x:y` can be
@@ -564,8 +564,9 @@ get_before_after_from_window <- function(window_size, align, time_type) {
564564
#' functions).
565565
#'
566566
#' @importFrom dplyr bind_rows mutate %>% arrange tibble select all_of
567-
#' @importFrom rlang enquo expr_label caller_arg
567+
#' @importFrom rlang enquo expr_label caller_arg quo_get_env
568568
#' @importFrom tidyselect eval_select
569+
#' @importFrom glue glue
569570
#' @importFrom purrr map map_lgl
570571
#' @importFrom data.table frollmean frollsum frollapply
571572
#' @importFrom lubridate as.period
@@ -577,8 +578,7 @@ get_before_after_from_window <- function(window_size, align, time_type) {
577578
#' # Compute a 7-day trailing average on cases.
578579
#' cases_deaths_subset %>%
579580
#' group_by(geo_value) %>%
580-
#' epi_slide_opt(cases, .f = data.table::frollmean, .window_size = 7) %>%
581-
#' dplyr::select(geo_value, time_value, cases, cases_7dav = slide_value_cases)
581+
#' epi_slide_opt(cases, .f = data.table::frollmean, .window_size = 7)
582582
#'
583583
#' # Same as above, but adjust `frollmean` settings for speed, accuracy, and
584584
#' # to allow partially-missing windows.
@@ -588,11 +588,11 @@ get_before_after_from_window <- function(window_size, align, time_type) {
588588
#' cases,
589589
#' .f = data.table::frollmean, .window_size = 7,
590590
#' algo = "exact", hasNA = TRUE, na.rm = TRUE
591-
#' ) %>%
592-
#' dplyr::select(geo_value, time_value, cases, cases_7dav = slide_value_cases)
591+
#' )
593592
epi_slide_opt <- function(
594593
.x, .col_names, .f, ...,
595594
.window_size = NULL, .align = c("right", "center", "left"),
595+
.prefix = NULL, .suffix = NULL, .new_col_names = NULL,
596596
.ref_time_values = NULL, .all_rows = FALSE) {
597597
assert_class(.x, "epi_df")
598598

@@ -644,21 +644,37 @@ epi_slide_opt <- function(
644644
)
645645
}
646646

647+
# The position of a given column can be differ between input `.x` and
648+
# `.data_group` since the grouping step by default drops grouping columns.
649+
# To avoid rerunning `eval_select` for every `.data_group`, convert
650+
# positions of user-provided `col_names` into string column names. We avoid
651+
# using `names(pos)` directly for robustness and in case we later want to
652+
# allow users to rename fields via tidyselection.
653+
col_names_quo <- enquo(.col_names)
654+
pos <- eval_select(col_names_quo, data = .x, allow_rename = FALSE)
655+
col_names_chr <- names(.x)[pos]
656+
647657
# Check that slide function `.f` is one of those short-listed from
648658
# `data.table` and `slider` (or a function that has the exact same
649659
# definition, e.g. if the function has been reexported or defined
650660
# locally).
651-
if (any(map_lgl(
652-
list(frollmean, frollsum, frollapply),
653-
~ identical(.f, .x)
654-
))) {
655-
f_from_package <- "data.table"
656-
} else if (any(map_lgl(
657-
list(slide_sum, slide_prod, slide_mean, slide_min, slide_max, slide_all, slide_any),
658-
~ identical(.f, .x)
659-
))) {
660-
f_from_package <- "slider"
661-
} else {
661+
f_possibilities <-
662+
tibble::tribble(
663+
~f, ~package, ~abbr,
664+
frollmean, "data.table", "av",
665+
frollsum, "data.table", "sum",
666+
frollapply, "data.table", "slide",
667+
slide_sum, "slider", "sum",
668+
slide_prod, "slider", "prod",
669+
slide_mean, "slider", "av",
670+
slide_min, "slider", "min",
671+
slide_max, "slider", "max",
672+
slide_all, "slider", "all",
673+
slide_any, "slider", "any",
674+
)
675+
f_info <- f_possibilities %>%
676+
filter(map_lgl(.data$f, ~ identical(.f, .x)))
677+
if (nrow(f_info) == 0L) {
662678
# `f` is from somewhere else and not supported
663679
cli_abort(
664680
c(
@@ -672,6 +688,7 @@ epi_slide_opt <- function(
672688
epiprocess__f = .f
673689
)
674690
}
691+
f_from_package <- f_info$package
675692

676693
user_provided_rtvs <- !is.null(.ref_time_values)
677694
if (!user_provided_rtvs) {
@@ -702,22 +719,59 @@ epi_slide_opt <- function(
702719
validate_slide_window_arg(.window_size, time_type)
703720
window_args <- get_before_after_from_window(.window_size, .align, time_type)
704721

722+
# Handle output naming
723+
assert_string(.prefix, null.ok = TRUE)
724+
assert_string(.suffix, null.ok = TRUE)
725+
assert_character(.new_col_names, len = length(col_names_chr), null.ok = TRUE)
726+
if ((!is.null(.prefix) || !is.null(.suffix)) && !is.null(.new_col_names)) {
727+
cli_abort(
728+
"Can't use both .prefix/.suffix and .new_col_names at the same time."
729+
)
730+
}
731+
if (is.null(.prefix) && is.null(.suffix) && is.null(.new_col_names)) {
732+
.suffix <- "_{.n}{.time_unit_abbr}{.align_abbr}{.f_abbr}"
733+
}
734+
if (!is.null(.prefix) || !is.null(.suffix)) {
735+
.prefix <- .prefix %||% ""
736+
.suffix <- .suffix %||% ""
737+
if (identical(.window_size, Inf)) {
738+
n <- "running_"
739+
time_unit_abbr <- ""
740+
align_abbr <- ""
741+
} else {
742+
n <- time_delta_to_n_steps(.window_size, time_type)
743+
time_unit_abbr <- time_type_unit_abbr(time_type)
744+
align_abbr <- c(right = "", center = "c", left = "l")[[.align]]
745+
}
746+
glue_env <- rlang::env(
747+
.n = n,
748+
.time_unit_abbr = time_unit_abbr,
749+
.align_abbr = align_abbr,
750+
.f_abbr = f_info$abbr,
751+
quo_get_env(col_names_quo)
752+
)
753+
.new_col_names <- unclass(
754+
glue(.prefix, .envir = glue_env) +
755+
col_names_chr +
756+
glue(.suffix, .envir = glue_env)
757+
)
758+
} else {
759+
# `.new_col_names` was provided by user; we don't need to do anything.
760+
}
761+
if (any(.new_col_names %in% names(.x))) {
762+
cli_abort(c(
763+
"Naming conflict between new columns and existing columns",
764+
"x" = "Overlapping names: {format_varnames(intersect(.new_col_names, names(.x)))}"
765+
))
766+
}
767+
result_col_names <- .new_col_names
768+
705769
# Make a complete date sequence between min(.x$time_value) and max(.x$time_value).
706770
date_seq_list <- full_date_seq(.x, window_args$before, window_args$after, time_type)
707771
all_dates <- date_seq_list$all_dates
708772
pad_early_dates <- date_seq_list$pad_early_dates
709773
pad_late_dates <- date_seq_list$pad_late_dates
710774

711-
# The position of a given column can be differ between input `.x` and
712-
# `.data_group` since the grouping step by default drops grouping columns.
713-
# To avoid rerunning `eval_select` for every `.data_group`, convert
714-
# positions of user-provided `col_names` into string column names. We avoid
715-
# using `names(pos)` directly for robustness and in case we later want to
716-
# allow users to rename fields via tidyselection.
717-
pos <- eval_select(enquo(.col_names), data = .x, allow_rename = FALSE)
718-
col_names_chr <- names(.x)[pos]
719-
# Always rename results to "slide_value_<original column name>".
720-
result_col_names <- paste0("slide_value_", col_names_chr)
721775
slide_one_grp <- function(.data_group, .group_key, ...) {
722776
missing_times <- all_dates[!(all_dates %in% .data_group$time_value)]
723777
# `frollmean` requires a full window to compute a result. Add NA values
@@ -843,6 +897,7 @@ epi_slide_opt <- function(
843897
epi_slide_mean <- function(
844898
.x, .col_names, ...,
845899
.window_size = NULL, .align = c("right", "center", "left"),
900+
.prefix = NULL, .suffix = NULL, .new_col_names = NULL,
846901
.ref_time_values = NULL, .all_rows = FALSE) {
847902
# Deprecated argument handling
848903
provided_args <- rlang::call_args_names(rlang::call_match())
@@ -885,6 +940,9 @@ epi_slide_mean <- function(
885940
...,
886941
.window_size = .window_size,
887942
.align = .align,
943+
.prefix = .prefix,
944+
.suffix = .suffix,
945+
.new_col_names = .new_col_names,
888946
.ref_time_values = .ref_time_values,
889947
.all_rows = .all_rows
890948
)
@@ -904,6 +962,7 @@ epi_slide_mean <- function(
904962
epi_slide_sum <- function(
905963
.x, .col_names, ...,
906964
.window_size = NULL, .align = c("right", "center", "left"),
965+
.prefix = NULL, .suffix = NULL, .new_col_names = NULL,
907966
.ref_time_values = NULL, .all_rows = FALSE) {
908967
# Deprecated argument handling
909968
provided_args <- rlang::call_args_names(rlang::call_match())
@@ -945,6 +1004,9 @@ epi_slide_sum <- function(
9451004
...,
9461005
.window_size = .window_size,
9471006
.align = .align,
1007+
.prefix = .prefix,
1008+
.suffix = .suffix,
1009+
.new_col_names = .new_col_names,
9481010
.ref_time_values = .ref_time_values,
9491011
.all_rows = .all_rows
9501012
)

R/utils.R

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ guess_time_type <- function(time_value, time_value_arg = rlang::caller_arg(time_
640640
return("day")
641641
} else if (inherits(time_value, "yearmonth")) {
642642
return("yearmonth")
643-
} else if (rlang::is_integerish(time_value)) {
643+
} else if (is_bare_integerish(time_value)) {
644644
return("integer")
645645
}
646646

@@ -1109,3 +1109,68 @@ validate_slide_window_arg <- function(arg, time_type, lower = 1, allow_inf = TRU
11091109
)
11101110
}
11111111
}
1112+
1113+
1114+
#' Convert a time delta to a compatible integerish number of steps between time values
1115+
#'
1116+
#' @param time_delta a vector that can be added to time values of time type
1117+
#' `time_type` to arrive at other time values of that time type, or
1118+
#' `r lifecycle::badge("experimental")` such a vector with Inf/-Inf entries mixed
1119+
#' in, if supported by the class of `time_delta`, even if `time_type` doesn't
1120+
#' necessarily support Inf/-Inf entries. Basically a slide window arg but
1121+
#' without sign and length restrictions.
1122+
#' @param time_type as in [`validate_slide_window_arg`]
1123+
#' @return [bare integerish][rlang::is_integerish] vector (with possible
1124+
#' infinite values) that produces the same result as `time_delta` when added
1125+
#' to time values of time type `time_type`. If the given time type does not
1126+
#' support infinite values, then it should produce +Inf or -Inf for analogous
1127+
#' entries of `time_delta`, and match the addition result match the addition
1128+
#' result for non-infinite values, and product +Inf / -Inf when match the sign
1129+
#' and of `time_delta`.
1130+
#'
1131+
#' @keywords internal
1132+
time_delta_to_n_steps <- function(time_delta, time_type) {
1133+
# could be S3 if we're willing to export
1134+
if (inherits(time_delta, "difftime")) {
1135+
output_units <- switch(time_type,
1136+
day = "days",
1137+
week = "weeks",
1138+
cli_abort("difftime objects not supported for time_type {format_chr_with_quotes(time_type)}")
1139+
)
1140+
units(time_delta) <- output_units # converts number accordingly, doesn't just set attr
1141+
n_steps <- vec_data(time_delta)
1142+
if (!is_bare_integerish(n_steps)) {
1143+
cli_abort("`time_delta` did not appear to contain only integerish numbers
1144+
of steps between time values of time type {format_chr_with_quotes(time_type)}")
1145+
}
1146+
n_steps
1147+
} else if (is_bare_integerish(time_delta)) { # (allows infinite values)
1148+
switch(time_type,
1149+
day = ,
1150+
week = ,
1151+
yearmonth = ,
1152+
integer = time_delta,
1153+
cli_abort("Invalid or unsupported time_type {format_chr_with_quotes(time_type)}")
1154+
)
1155+
} else {
1156+
cli_abort("Invalid or unsupported kind of `time_delta`")
1157+
}
1158+
}
1159+
1160+
# Using these unit abbreviations happens to make our automatic slide output
1161+
# naming look like taking ISO-8601 duration designations, removing the P, and
1162+
# lowercasing any characters. Fortnightly or sub-daily time types would need an
1163+
# adjustment to remain consistent.
1164+
time_type_unit_abbrs <- c(
1165+
day = "d",
1166+
week = "w",
1167+
yearmon = "m"
1168+
)
1169+
1170+
time_type_unit_abbr <- function(time_type) {
1171+
maybe_unit_abbr <- time_type_unit_abbrs[time_type]
1172+
if (is.na(maybe_unit_abbr)) {
1173+
cli_abort("Cannot determine the units of time type {format_chr_with_quotes(time_type)}")
1174+
}
1175+
maybe_unit_abbr
1176+
}

man/epi_slide.Rd

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)