Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ref_group_last for custom split funs #1087

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,4 @@ Collate:
'utils_factor.R'
'utils_grid.R'
'utils_rtables.R'
'utils_split_funs.R'
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,9 @@ export(has_fraction_in_cols)
export(has_fractions_difference)
export(imputation_rule)
export(keep_content_rows)
export(keep_level_order)
export(keep_rows)
export(level_order)
export(logistic_regression_cols)
export(logistic_summary_by_flag)
export(month2day)
Expand All @@ -235,6 +237,7 @@ export(prop_strat_wilson)
export(prop_wald)
export(prop_wilson)
export(reapply_varlabels)
export(ref_group_position)
export(s_compare)
export(s_count_occurrences)
export(s_count_occurrences_by_grade)
Expand Down
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# tern 0.9.2.9001

### New Features
* Added `ref_group_position` function to place the reference group facet last, first or at a certain position.
* Added `keep_level_order` split function to retain original order of levels in a split.
* Added `level_order` split function to reorder manually the levels.

### Miscellaneous
* Specified minimal version of package dependencies.

Expand Down
185 changes: 185 additions & 0 deletions R/utils_split_funs.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
#' Custom Split Functions
#'
#' @description `r lifecycle::badge("stable")`
#'
#' Collection of useful functions that are expanding on the core list of functions
#' provided by `rtables`. See [rtables::custom_split_funs] and [rtables::make_split_fun()]
#' for more information on how to make a custom split function. All these functions
#' work with [split_rows_by()] argument `split_fun` to modify the way the split
#' happens. For other split functions, consider consulting [`rtables::split_funcs`].
#'
#' @inheritParams rtables::split_funcs
#' @param .spl_context (`data.frame`) \cr detailed description of the current split (or subsetting).
#' Please consider consulting [rtables::spl_context] for more information.
#'
#' @seealso [rtables::make_split_fun()]
#'
#' @name utils_split_funs
Melkiades marked this conversation as resolved.
Show resolved Hide resolved
NULL

#' @describeIn utils_split_funs split function to place reference group facet at a specific position
#' during post-processing stage.
#'
#' @param position (`string` or `integer`)\cr should it be `"first"` or `"last"` or in a specific position?
#'
#' @return
#' * `ref_group_position` returns an utility function that puts the reference group
#' as first, last or at a certain position and needs to be assigned to `split_fun`.
#'
#' @examples
#' library(dplyr)
#'
#' dat <- data.frame(
#' x = factor(letters[1:5], levels = letters[5:1]),
#' y = 1:5
#' )
#'
#' # With rtables layout functions
#' basic_table() %>%
#' split_cols_by("x", ref_group = "c", split_fun = ref_group_position("last")) %>%
#' analyze("y") %>%
#' build_table(dat)
#'
#' # With tern layout funcitons
#' adtte_f <- tern_ex_adtte %>%
#' filter(PARAMCD == "OS") %>%
#' mutate(
#' AVAL = day2month(AVAL),
#' is_event = CNSR == 0
#' )
#'
#' basic_table() %>%
#' split_cols_by(var = "ARMCD", ref_group = "ARM B", split_fun = ref_group_position("first")) %>%
#' add_colcounts() %>%
#' surv_time(
#' vars = "AVAL",
#' var_labels = "Survival Time (Months)",
#' is_event = "is_event",
#' ) %>%
#' build_table(df = adtte_f)
#'
#' basic_table() %>%
#' split_cols_by(var = "ARMCD", ref_group = "ARM B", split_fun = ref_group_position(2)) %>%
#' add_colcounts() %>%
#' surv_time(
#' vars = "AVAL",
#' var_labels = "Survival Time (Months)",
#' is_event = "is_event",
#' ) %>%
#' build_table(df = adtte_f)
#'
#' @export
ref_group_position <- function(position = "first") {
make_split_fun(
post = list(
function(splret, spl, fulldf) {
if (!"ref_group_value" %in% slotNames(spl)) {
stop("Reference group is undefined.")
}

spl_var <- rtables:::spl_payload(spl)
fulldf[[spl_var]] <- factor(fulldf[[spl_var]])
init_lvls <- levels(fulldf[[spl_var]])

if (!all(names(splret$values) %in% init_lvls)) {
stop("This split function does not work with combination facets.")
}

ref_group_pos <- which(init_lvls == rtables:::spl_ref_group(spl))
pos_choices <- c("first", "last")
if (checkmate::test_choice(position, pos_choices) && position == "first") {
pos <- 0
} else if (checkmate::test_choice(position, pos_choices) && position == "last") {
pos <- length(init_lvls)
} else if (checkmate::test_int(position, lower = 1, upper = length(init_lvls))) {
pos <- position - 1
} else {
stop("Wrong input for ref group position. It must be 'first', 'last', or a integer.")
}

reord_lvls <- append(init_lvls[-ref_group_pos], init_lvls[ref_group_pos], after = pos)
ord <- match(reord_lvls, names(splret$values))

make_split_result(
splret$values[ord],
splret$datasplit[ord],
splret$labels[ord]
)
}
)
)
}
#' @describeIn utils_split_funs split function to keep original order of factor
#' levels in the split.
#'
#' @return
#' * `keep_level_order` returns an utility function that keeps the original levels'.
#' It needs to be assigned to `split_fun`.
#'
#' @examples
#' # keep_level_order --------
#' # Even if default would bring ref_group first, the original order puts it last
#' basic_table() %>%
#' split_cols_by("Species", ref_group = "virginica", split_fun = keep_level_order) %>%
#' analyze("Sepal.Length") %>%
#' build_table(iris)
#'
#' @export
keep_level_order <- make_split_fun(
post = list(
function(splret, spl, fulldf, ...) {
ord <- order(names(splret$values))
make_split_result(
splret$values[ord],
splret$datasplit[ord],
splret$labels[ord]
)
}
)
)
#' @describeIn utils_split_funs split function to change level order based on a `integer`
#' vector or a `character` vector that represent the split variable's factor levels.
#'
#' @param order (`character` or `integer`)\cr vector of ordering indexes for the split facets.
#'
#' @return
#' * `keep_level_order` returns an utility function that changes the original levels' order,
#' depending on input `order` and split levels.
#'
#' @examples
#' # level_order --------
#' # Even if default would bring ref_group first, the original order puts it last
#' basic_table() %>%
#' split_cols_by("Species", split_fun = level_order(c(1, 3, 2))) %>%
#' analyze("Sepal.Length") %>%
#' build_table(iris)
#'
#' # character vector
#' new_order <- level_order(levels(iris$Species)[c(1, 3, 2)])
#' basic_table() %>%
#' split_cols_by("Species", ref_group = "virginica", split_fun = new_order) %>%
#' analyze("Sepal.Length") %>%
#' build_table(iris)
#'
#' @export
level_order <- function(order) {
make_split_fun(
post = list(
function(splret, spl, fulldf, ...) {
if (checkmate::test_integerish(order)) {
checkmate::assert_integerish(order, lower = 1, upper = length(splret$values))
ord <- order
} else {
checkmate::assert_character(order, len = length(splret$values))
checkmate::assert_set_equal(order, names(splret$values), ordered = FALSE)
ord <- match(order, names(splret$values))
}
make_split_result(
splret$values[ord],
splret$datasplit[ord],
splret$labels[ord]
)
}
)
)
}
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ reference:
- split_cols_by_groups
- to_string_matrix
- groups_list_to_df
- utils_split_funs

- title: rtables Formatting Functions
desc: These functions provide customized formatting rules to work with the
Expand Down
147 changes: 147 additions & 0 deletions man/utils_split_funs.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading