case_when: A general vectorised if.

Description Usage Arguments Value Examples

View source: R/case_when.R

Description

This function allows you to vectorise mutiple if and else if statements. It is an R equivalent of the SQL CASE WHEN statement.

Usage

1

Arguments

...

A sequence of two-sided formulas. The left hand side (LHS) determines which values match this case. The right hand side (RHS) provides the replacement value.

The LHS must evaluate to a logical vector. Each logical vector can either have length 1 or a common length. All RHSs must evaluate to the same type of vector.

Value

A vector as long as the longest LHS, with the type (and attributes) of the first RHS. Inconsistent lengths of types will generate an error.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
x <- 1:50
case_when(
  x %% 35 == 0 ~ "fizz buzz",
  x %% 5 == 0 ~ "fizz",
  x %% 7 == 0 ~ "buzz",
  TRUE ~ as.character(x)
)

# Like an if statement, the arguments are evaluated in order, so you must
# proceed from the most specific to the most general. This won't work:
case_when(
  TRUE ~ as.character(x),
  x %%  5 == 0 ~ "fizz",
  x %%  7 == 0 ~ "buzz",
  x %% 35 == 0 ~ "fizz buzz"
)

sctyner/dplyr050 documentation built on May 17, 2019, 2:22 p.m.