base_when: Defines factors using logical objects

View source: R/base_when.r

base_whenR Documentation

Defines factors using logical objects

Description

A base-R approximation of case_when() from 'dplyr'. Unlike case_when(), base_when() returns a factor. The levels will be ordered according to the order included in ... (see below).

Usage

base_when(..., as_factor = TRUE, string_for_na = "")

Arguments

...

conditions for defining the replacement values, specified as a named list, with each element in 'label'=logical_vector format, with the levels listed in the desired order

as_factor

logical, controlling whether the function should return a factor

string_for_na

string value that will be converted to NA

Value

a factor

Examples

# load data
data(nhanes)

# define cholesterol
nhanes<-nhanes |>
  transform(
    cholesterol=base_when(
      'Desirable' = (lbxtc<200),
      'Borderline high' = (lbxtc>=200)&(lbxtc<240),
      'High' = (lbxtc>=240)
    )
  )

baseverse documentation built on April 29, 2026, 1:08 a.m.