fcase
fcase.Rd
fcase
is a fast implementation of SQL CASE WHEN
statement for R. Conceptually, fcase
is a nested version of fifelse
(with smarter implementation than manual nesting). It is comparable to dplyr::case_when
and supports bit64
's integer64
and nanotime
classes.
Arguments
- ...
A sequence consisting of logical condition (
when
)-resulting value (value
) pairs in the following orderwhen1, value1, when2, value2, ..., whenN, valueN
. Logical conditionswhen1, when2, ..., whenN
must all have the same length, type and attributes. Eachvalue
may either share length withwhen
or be length 1. Please see Examples section for further details.- default
Default return value,
NA
by default, for when all of the logical conditionswhen1, when2, ..., whenN
areFALSE
or missing for some entries.
Value
Vector with the same length as the logical conditions (when
) in ...
, filled with the corresponding values (value
) from ...
, or eventually default
. Attributes of output values value1, value2, ...valueN
in ...
are preserved.
Examples
x = 1:10
fcase(
x < 5L, 1L,
x > 5L, 3L
)
#> [1] 1 1 1 1 NA 3 3 3 3 3
fcase(
x < 5L, 1L:10L,
x > 5L, 3L:12L
)
#> [1] 1 2 3 4 NA 8 9 10 11 12
# Lazy evaluation example
fcase(
x < 5L, 1L,
x >= 5L, 3L,
x == 5L, stop("provided value is an unexpected one!")
)
#> [1] 1 1 1 1 3 3 3 3 3 3
# fcase preserves attributes, example with dates
fcase(
x < 5L, as.Date("2019-10-11"),
x > 5L, as.Date("2019-10-14")
)
#> [1] "2019-10-11" "2019-10-11" "2019-10-11" "2019-10-11" NA
#> [6] "2019-10-14" "2019-10-14" "2019-10-14" "2019-10-14" "2019-10-14"
# fcase example with factor; note the matching levels
fcase(
x < 5L, factor("a", levels=letters[1:3]),
x > 5L, factor("b", levels=letters[1:3])
)
#> [1] a a a a <NA> b b b b b
#> Levels: a b c
# Example of using the 'default' argument
fcase(
x < 5L, 1L,
x > 5L, 3L,
default = 5L
)
#> [1] 1 1 1 1 5 3 3 3 3 3