fifelse {data.table}R Documentation

Fast ifelse


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.


  fifelse(test, yes, no, na=NA)



A logical vector.

yes, no

Values to return depending on TRUE/FALSE element of test. They must be the same type and be either length 1 or the same length of test.


Value to return if an element of test is NA. It must be the same type as yes and no and length 1. Default value NA. NULL is treated as NA.


In contrast to ifelse attributes are copied from yes to the output. This is useful when returning Date, factor or other classes.


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.

See Also



x = c(1:4, 3:2, 1:4)
fifelse(x > 2L, x, x - 1L)

# 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)
fifelse(dates == "2011-01-01", dates - 1, dates)
yes = factor(c("a","b","c"))
no = yes[1L]
ifelse(c(TRUE,FALSE,TRUE), yes, no)
fifelse(c(TRUE,FALSE,TRUE), yes, no)

# Example of using the 'na' argument
fifelse(test = c(-5L:5L < 0L, NA), yes = 1L, no = 0L, na = 2L)

[Package data.table version 1.12.9 Index]