handle_subset_arg: Handle Function Subset Argument

View source: R/utils.R

handle_subset_argR Documentation

Handle Function Subset Argument

Description

This function is intended to be used inside other functions to handle that function's argument subset.

Usage

handle_subset_arg(
  subset_arg_nm = "subset",
  dataset = emptyenv(),
  function_env = parent.frame(1L),
  enclosing_env = parent.frame(2L),
  function_call = sys.call(1L)
)

subset_and(subset1, subset2)

Arguments

subset_arg_nm

⁠[character]⁠ (mandatory, default "subset")

name of subset argument of the function where this function is used

dataset

⁠[environment, data.frame]⁠ (optional, default emptyenv())

if subset is an expression, it can evaluated in this context; see ?eval

function_env

⁠[environment]⁠ (optional, default parent.frame(1L))

env where to collect subset expression from — the default should work

enclosing_env

⁠[environment]⁠ (optional, default parent.frame(2L))

env where to continue scoping after dataset; think of this as the env where dataset exists if it is a data.frame

function_call

⁠[call]⁠ (optional, default sys.call(1L))

in case a warning is emitted due to NA values in the subset, this call is passed to base::simpleWarning.

subset1

⁠[NULL, integer, logical]⁠ (mandatory, no default) subset to combine with subset2

subset2

⁠[NULL, integer, logical]⁠ (mandatory, no default) subset to combine with subset1

Details

The subset arg can be one of logical, integer, or NULL. NULL implies no subset. logical must be of length nrow(dataset), if dataset is a data.frame. Similarly, integer subset must have values in between -nrow(dataset) and nrow(dataset).

subset_and is used to combine two results of handle_subset_arg. If both subset1 and subset2 are logical, this is the same as subset1 & subset2. However, this function handles all the possible pairs of classes of subset1 and subset2 intelligently.

Functions

  • subset_and(): intersect two subsetting vectors

Examples


my_fun <- function(x, subset = NULL) {
  stopifnot(is.data.frame(x))
  evaluated_subset <- handle_subset_arg(dataset = x)
  if (is.null(evaluated_subset)) {
    n <- nrow(x)
  } else {
    n <- length(x[[1]][evaluated_subset])
  }
  return(n)
}

df <- data.frame(a = 1:5, b = 5:1)
my_fun(x = df, subset = df$a > 3)
my_fun(x = df, subset = a > 3)
my_fun(x = df, subset = 1:3)

CancerRegistryOfNorway/nordcancore documentation built on April 29, 2024, 4:40 p.m.