Fast ifelse
fifelse.Rd
fifelse
is a faster and more robust replacement of ifelse
. It is comparable to dplyr::if_else
and hutils::if_else
. It returns a value with the same length as test
filled with corresponding values from yes
, no
or eventually na
, depending on test
. Supports bit64
's integer64
and nanotime
classes.
Arguments
- test
A logical vector.
- yes, no
Values to return depending on
TRUE
/FALSE
element oftest
. They must be the same type and be either length1
or the same length oftest
.- na
Value to return if an element of
test
isNA
. It must be the same type asyes
andno
and its length must be either1
or the same length oftest
. Default valueNA
.NULL
is treated asNA
.
Details
In contrast to ifelse
attributes are copied from the first non-NA
argument to the output. This is useful when returning Date
, factor
or other classes.
Unlike ifelse
, fifelse
evaluates both yes
and no
arguments for type checking regardless of the result of test
. This means that neither yes
nor no
should be recursive function calls. For recursion, use fcase
instead.
Value
A vector of the same length as test
and attributes as yes
. Data values are taken from the values of yes
and no
, eventually na
.
Examples
x = c(1:4, 3:2, 1:4)
fifelse(x > 2L, x, x - 1L)
#> [1] 0 1 3 4 3 1 0 1 3 4
# unlike ifelse, fifelse preserves attributes, taken from the 'yes' argument
dates = as.Date(c("2011-01-01","2011-01-02","2011-01-03","2011-01-04","2011-01-05"))
ifelse(dates == "2011-01-01", dates - 1, dates)
#> [1] 14974 14976 14977 14978 14979
fifelse(dates == "2011-01-01", dates - 1, dates)
#> [1] "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
yes = factor(c("a","b","c"))
no = yes[1L]
ifelse(c(TRUE,FALSE,TRUE), yes, no)
#> [1] 1 1 3
fifelse(c(TRUE,FALSE,TRUE), yes, no)
#> [1] a a c
#> Levels: a b c
# Example of using the 'na' argument
fifelse(test = c(-5L:5L < 0L, NA), yes = 1L, no = 0L, na = 2L)
#> [1] 1 1 1 1 1 0 0 0 0 0 0 2
# Example showing both 'yes' and 'no' arguments are evaluated, unlike ifelse
fifelse(1 == 1, print("yes"), print("no"))
#> [1] "yes"
#> [1] "no"
#> [1] "yes"
ifelse(1 == 1, print("yes"), print("no"))
#> [1] "yes"
#> [1] "yes"