| iif {kit} | R Documentation |
Fast if else
Description
iif is a faster and more robust replacement of ifelse. It is comparable to dplyr::if_else, hutils::if_else and data.table::fifelse. It returns a value with the same length as test filled with corresponding values from yes, no or eventually na, depending on test. It does not support S4 classes.
Usage
iif(test, yes, no, na=NULL, tprom=FALSE, nThread=getOption("kit.nThread"))
Arguments
test |
A logical vector. |
yes, no |
Values to return depending on |
na |
Value to return if an element of |
tprom |
Argument to indicate whether type promotion of |
nThread |
A integer for the number of threads to use with openmp. Default value is |
Details
In contrast to ifelse attributes are copied from yes to the output. This is useful when returning Date, factor or other classes.
Like dplyr::if_else and hutils::if_else, the na argument is by default set to NULL. This argument is set to NA in data.table::fifelse.
Similarly to dplyr::if_else and when tprom=FALSE, iif requires same type for arguments yes and no. This is not strictly the case for data.table::fifelse which will coerce integer to double.
When tprom=TRUE, iif behavior is similar to base::ifelse in the sense that it will promote or coerce yes and noto the "highest" used type. Note, however, that unlike base::ifelse attributes are still conserved.
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.
Author(s)
Morgan Jacob
See Also
Examples
x = c(1:4, 3:2, 1:4)
iif(x > 2L, x, x - 1L)
# unlike ifelse, iif 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)
iif(dates == "2011-01-01", dates - 1, dates)
yes = factor(c("a","b","c"))
no = yes[1L]
ifelse(c(TRUE,FALSE,TRUE), yes, no)
iif(c(TRUE,FALSE,TRUE), yes, no)
# Example of using the 'na' argument
iif(test = c(-5L:5L < 0L, NA), yes = 1L, no = 0L, na = 2L)
# Example of using the 'tprom' argument
iif(test = c(-5L:5L < 0L, NA), yes = 1L, no = "0", na = 2L, tprom = TRUE)