Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

switch_type

Dispatch on base types


Description

Soft-deprecated lifecycleExperimental lifecycle

switch_type() is equivalent to switch(type_of(x, ...)), while switch_class() switchpatches based on class(x). The coerce_ versions are intended for type conversion and provide a standard error message when conversion fails.

Usage

switch_type(.x, ...)

coerce_type(.x, .to, ...)

switch_class(.x, ...)

coerce_class(.x, .to, ...)

Arguments

.x

An object from which to dispatch.

...

Named clauses. The names should be types as returned by type_of().

.to

This is useful when you switchpatch within a coercing function. If supplied, this should be a string indicating the target type. A catch-all clause is then added to signal an error stating the conversion failure. This type is prettified unless .to inherits from the S3 class "AsIs" (see base::I()).

Examples

switch_type(3L,
  double = "foo",
  integer = "bar",
  "default"
)

# Use the coerce_ version to get standardised error handling when no
# type matches:
to_chr <- function(x) {
  coerce_type(x, "a chr",
    integer = as.character(x),
    double = as.character(x)
  )
}
to_chr(3L)

# Strings have their own type:
switch_type("str",
  character = "foo",
  string = "bar",
  "default"
)

# Use a fallthrough clause if you need to dispatch on all character
# vectors, including strings:
switch_type("str",
  string = ,
  character = "foo",
  "default"
)

# special and builtin functions are treated as primitive, since
# there is usually no reason to treat them differently:
switch_type(base::list,
  primitive = "foo",
  "default"
)
switch_type(base::`$`,
  primitive = "foo",
  "default"
)

# closures are not primitives:
switch_type(rlang::switch_type,
  primitive = "foo",
  "default"
)

rlang

Functions for Base Types and Core R and 'Tidyverse' Features

v0.4.11
MIT + file LICENSE
Authors
Lionel Henry [aut, cre], Hadley Wickham [aut], mikefc [cph] (Hash implementation based on Mike's xxhashlite), Yann Collet [cph] (Author of the embedded xxHash library), RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.